SavCpp8PowerPointsSavitch_ch_13_第1页
SavCpp8PowerPointsSavitch_ch_13_第2页
SavCpp8PowerPointsSavitch_ch_13_第3页
SavCpp8PowerPointsSavitch_ch_13_第4页
SavCpp8PowerPointsSavitch_ch_13_第5页
已阅读5页,还剩84页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Chapter13,PointersandLinkedLists,Overview,13.1NodesandLinkedLists13.2StacksandQueues,Slide13-3,13.1,NodesandLinkedLists,NodesandLinkedLists,Slide13-5,AlinkedlistisalistthatcangrowandshrinkwhiletheprogramisrunningAlinkedlistisconstructedusingpointersAlinkedlistoftenconsistsofstructsorclassesthatcontainapointervariableconnectingthemtootherdynamicvariablesAlinkedlistcanbevisualizedasitems,drawnasboxes,connectedtootheritemsbyarrows,Nodes,TheboxesinthepreviousdrawingrepresentthenodesofalinkedlistNodescontainthedataitem(s)andapointerthatcanpointtoanothernodeofthesametypeThepointerspointtotheentirenode,notanindividualitemthatmightbeinthenodeThearrowsinthedrawingrepresentpointers,Slide13-6,Display13.1,ImplementingNodes,NodesareimplementedinC+asstructsorclassesExample:Astructuretostoretwodataitemsandapointertoanothernodeofthesametype,alongwithatypedefinitionmightbe:structListNodestringitem;intcount;ListNode*link;typedefListNode*ListNodePtr;,Slide13-7,TheheadofaList,Theboxlabeledhead,indisplay13.1,isnotanode,butapointervariablethatpointstoanodePointervariableheadisdeclaredas:ListNodePtrhead;,Slide13-8,AccessingItemsinaNode,Usingthediagramof13.1,thisisonewaytochangethenumberinthefirstnodefrom10to12:(*head).count=12;headisapointervariableso*headisthenodethatheadpointstoTheparenthesesarenecessarybecausethedotoperator.hashigherprecedencethanthedereferenceoperator*,Slide13-9,TheArrowOperator,Thearrowoperator-combinestheactionsofthedereferencingoperator*andthedotoperatortospecifyamemberofastructorobjectpointedtobyapointer(*head).count=12;canbewrittenashead-count=12;Thearrowoperatorismorecommonlyused,Slide13-10,Display13.2,NULL,ThedefinedconstantNULLisusedasAnendmarkerforalinkedlistAprogramcanstepthroughalistofnodesbyfollowingthepointers,butwhenitfindsanodecontainingNULL,itknowsithascometotheendofthelistThevalueofapointerthathasnothingtopointtoThevalueofNULLis0AnypointercanbeassignedthevalueNULL:double*there=NULL;,Slide13-11,ToUseNULL,AdefinitionofNULLisfoundinseverallibraries,includingandAusingdirectiveisnotneededforNULL,Slide13-12,LinkedLists,ThediagraminDisplay13.2depictsalinkedlistAlinkedlistisalistofnodesinwhicheachnodehasamembervariablethatisapointerthatpointstothenextnodeinthelistThefirstnodeiscalledtheheadThepointervariablehead,pointstothefirstnodeThepointernamedheadisnottheheadofthelistitpointstotheheadofthelistThelastnodecontainsapointersettoNULL,Slide13-13,BuildingaLinkedList:Thenodedefinition,Letsbeginwithasimplenodedefinition:structNodeintdata;Node*link;typedefNode*NodePtr;,Slide13-14,BuildingaLinkedList:DeclaringPointerVariablehead,Withthenodedefinedandatypedefinitiontomakeorcodeeasiertounderstand,wecandeclarethepointervariablehead:NodePtrhead;headisapointervariablethatwillpointtotheheadnodewhenthenodeiscreated,Slide13-15,BuildingaLinkedList:CreatingtheFirstNode,Tocreatethefirstnode,theoperatornewisusedtocreateanewdynamicvariable:head=newNode;Nowheadpointstothefirst,andonly,nodeinthelist,Slide13-16,BuildingaLinkedList:InitializingtheNode,Nowthatheadpointstoanode,weneedtogivevaluestothemembervariablesofthenode:head-data=3;head-link=NULL;Sincethisnodeisthelastnode,thelinkissettoNULL,Slide13-17,Functionhead_insert,Itwouldbebettertocreateafunctiontoinsertnodesattheheadofalist,suchas:voidhead_insert(NodePtrThefirstparameterisaNodePtrparameterthatpointstothefirstnodeinthelinkedlistThesecondparameteristhenumbertostoreinthelisthead_insertwillcreateanewnodeforthenumberThenumberwillbecopiedtothenewnodeThenewnodewillbeinsertedinthelistasthenewheadnode,Slide13-18,Pseudocodeforhead_insert,Createanewdynamicvariablepointedtobytemp_ptrPlacethedatainthenewnodecalled*temp_ptrMaketemp_ptrslinkvariablepointtotheheadnodeMaketheheadpointerpointtotemp_ptr,Slide13-19,Display13.3,Translatinghead_inserttoC+,Thepseudocodeforhead_insertcanbewritteninC+usingtheselinesinplaceofthelinesofpseudocode:NodePtrtemp_ptr;/createthetemporarypointertemp_ptr=newNode;/createthenewnodetemp_ptr-data=the_number;/copythenumbertemp_ptr-link=head;/newnodepointstofirstnodehead=temp_ptr;/headpointstonew/firstnode,Slide13-20,Display13.4,AnEmptyList,AlistwithnothinginitiscalledanemptylistAnemptylinkedlisthasnoheadnodeTheheadpointerofanemptylistisNULLhead=NULL;Anyfunctionswrittentomanipulatealinkedlistshouldchecktoseeifitworksontheemptylist,Slide13-21,LosingNodes,Youmightbetemptedtowritehead_insertusingtheheadpointertoconstructthenewnode:head=newNode;head-data=the_number;NowtoattachthenewnodetothelistThenodethatheadusedtopointtoisnowlost!,Slide13-22,Display13.5,MemoryLeaks,NodesthatarelostbyassigningtheirpointersanewaddressarenotaccessibleanylongerTheprogramhasnowaytorefertothenodesandcannotdeletethemtoreturntheirmemorytothefreestoreProgramsthatlosenodeshaveamemoryleakSignificantmemoryleakscancausesystemcrashes,Slide13-23,SearchingaLinkedList,Todesignafunctionthatwilllocateaparticularnodeinalinkedlist:Wewantthefunctiontoreturnapointertothenodesowecanusethedataifwefindit,elsereturnNULLThelinkedlistisoneargumenttothefunctionThedatawewishtofindistheotherargumentThisdeclarationwillwork:NodePtrsearch(NodePtrhead,inttarget);,Slide13-24,Functionsearch,RefiningourfunctionWewillusealocalpointervariable,namedhere,tomovethroughthelistcheckingforthetargetTheonlywaytomovearoundalinkedlististofollowpointersWewillstartwithherepointingtothefirstnodeandmovethepointerfromnodetonodefollowingthepointeroutofeachnode,Slide13-25,Display13.6,Pseudocodeforsearch,Makepointervariableherepointtotheheadnodewhile(heredoesnotpointtoanodecontainingtargetANDheredoesnotpointtothelastnode)makeherepointtothenextnodeIf(herepointstoanodecontainingthetarget)returnhere;elsereturnNULL;,Slide13-26,MovingThroughtheList,ThepseudocodeforsearchrequiresthatpointerherestepthroughthelistHowdoesherefollowthepointersfromnodetonode?Whenherepointstoanode,here-linkistheaddressofthenextnodeTomakeherepointtothenextnode,maketheassignment:here=here-link;,Slide13-27,ARefinementofsearch,Thesearchfunctioncanberefinedinthisway:here=head;while(here-data!=target,Slide13-28,Checkforlastnode,SearchinganEmptyList,OursearchalgorithmhasaproblemIfthelistisempty,hereequalsNULLbeforethewhileloopsohere-dataisundefinedhere-linkisundefinedTheemptylistrequiresaspecialcaseinoursearchfunctionArefinedsearchfunctionthathandlesanemptylistisshownin,Slide13-29,Display13.7,PointersasIterators,AniteratorisaconstructthatallowsyoutocyclethroughthedataitemsinadatastructuretoperformanactiononeachitemAniteratorcanbeanobjectofaniteratorclass,anarrayindex,orsimplyapointerAgeneraloutlineusingapointerasaniterator:Node_Type*iter;for(iter=Head;iter!=NULL;iter=iter-Link)/performtheactiononthenodeiterpointstoHeadisapointertotheheadnodeofthelist,Slide13-30,IteratorExample,Usingthepreviousoutlineofaniteratorwecandisplaythecontentsofalinkedlistinthisway:NodePtriter;for(iter=Head;iter!=NULL;iter=iter-Link)coutdata);,Slide13-31,InsertingaNodeInsideaList,Toinsertanodeafteraspecifiednodeinthelinkedlist:UseanotherfunctiontoobtainapointertothenodeafterwhichthenewnodewillbeinsertedCallthepointerafter_meUsefunctioninsert,declaredheretoinsertthenode:voidinsert(NodePtrafter_me,intthe_number);,Slide13-32,Display13.8,InsertingtheNewNode,Functioninsertcreatesthenewnodejustashead_insertdidWedonotwantournewnodeattheheadofthelisthowever,soWeusethepointerafter_metoinsertthenewnode,Slide13-33,InsertingtheNewNode,Thiscodewillaccomplishtheinsertionofthenewnode,pointedtobytemp_ptr,afterthenodepointedtobyafter_me:temp_ptr-link=after_me-link;after_me-link=temp_ptr;,Slide13-34,Caution!,TheorderofpointerassignmentsiscriticalIfwechangedafter_me-linktopointtotemp_ptrfirst,wewouldloosetherestofthelist!Thecompleteinsertfunctionisshownin,Slide13-35,Display13.9,FunctioninsertAgain,NoticethatinsertingintoalinkedlistrequiresthatyouonlychangetwopointersThisistrueregardlessofthelengthofthelistUsinganarrayforthelistwouldinvolvecopyingasmanyasallofthearrayelementstonewlocationstomakeroomforthenewitemInsertingintoalinkedlistisoftenmoreefficientthaninsertingintoanarray,Slide13-36,RemovingaNode,ToremoveanodefromalinkedlistPositionapointer,before,topointatthenodepriortothenodetoremovePositionapointer,discard,topointatthenodetoremovePerform:before-link=discard-link;Thenodeisremovedfromthelist,butisstillinmemoryReturn*discardtothefreestore:deletediscard;,Slide13-37,Display13.10,AssignmentWithPointers,Ifhead1andhead2arepointervariablesandhead1pointstotheheadnodeofalist:head2=head1;causeshead2andhead1topointtothesamelistThereisonlyonelist!Ifyouwanthead2topointtoaseparatecopy,youmustcopythelistnodebynodeoroverloadtheassignmentoperatorappropriately,Slide13-38,VariationsonLinkedLists,ManyotherdatastructurescanbeconstructedusingnodesandpointersDoubly-LinkedListEachnodehastwolinks,onetothenextnodeandonetothepreviousnodeAllowseasytraversalofthelistinbothdirectionsstructNodeintdata;Node*forward_link;Node*back_link;,Slide13-39,Display13.11,BinaryTree,Atreeisadatastructurethatlookslikeanupside-downtreewiththerootatthetopNocyclesInabinarytreeeachnodehasatmosttwolinks,Slide13-40,structTreeNodeintdata;TreeNode*left_link;TreeNode*right_link;,Display13.12,LinkedListofClasses,Theprecedingexamplescreatedlinkedlistsofstructs.Wecanalsocreatelinkedlistsusingclasses.LogictouseaclassisidenticalexceptthesyntaxofusinganddefiningaclassshouldbesubstitutedinplaceofthatforastructInterfaceandDefinitionforaNodeClass,Slide13-41,Display13.13,Display13.14(1-2),ProgramusingtheNodeclass,WecancreatealinkedlistofnumbersusingtheNodeclass.,Slide13-42,Display13.15(1-3),Section13.1Conclusion,CanyouWritetypedefinitionsforthenodesandpointersinalinkedlist?CallthenodetypeNodeTypeandcallthepointertypePointerType.Thelinkedlistswillbelistsofletters.Explainwhyinsertingintoanarraycanbelessefficientthaninsertingintoalinkedlist?,Slide13-43,13.2,StacksandQueues,ALinkedListApplication,AstackisadatastructurethatretrievesdatainthereverseorderthedatawasstoredIfA,B,andthenCareplacedinastack,theywillberemovedintheorderC,B,andthenAAstackisalast-in/first-outdatastructurelikethestackofplatesinacafeteria;addingaplatepushesdownthestackandthetopplateisthefirstoneremoved,Slide13-45,Display13.16,ProgramExample:AStackClass,WewillcreateastackclasstostorecharactersAddinganitemtoastackispushingontothestackMemberfunctionpushwillperformthistaskRemovinganitemfromthestackispoppingthetheitemoffthestackMemberfunctionpopwillperformthistaskcontainsthestackclassinterface,Slide13-46,Display13.17,UsingthestackClass,demonstratestheuseofthestackclass,Slide13-47,Display13.18(1-2),Functionpush,ThepushfunctionaddsanitemtothestackItusesaparameterofthetypestoredinthestackvoidpush(charthe_symbol);Pushinganitemontothestackispreciselythesametaskaccomplishedbyfunctionhead_insertofthelinkedlistForastack,apointernamedtopisusedinsteadofapointernamedhead,Slide13-48,Functionpop,Thepopfunctionreturnstheitemthatwasatthetopofthestackcharpop();Beforepoppinganitemfromastack,popchecksthatthestackisnotemptypopstoresthetopiteminalocalvariableresult,andtheitemispoppedby:top=top-link;Atemporarypointermustpointtotheoldtopitemsoitcanbedeletedtopreventamemoryleakpopthenreturnsvariableresult,Slide13-49,EmptyStack,AnemptystackisidentifiedbysettingthetoppointertoNULLtop=NULL;,Slide13-50,TheCopyConstructor,Becausethestackclassusesapointerandcreatesnewnodesusingnew,acopyconstructorisneededThecopyconstructor(aself-testexercise)mustmakeacopyofeachiteminthestackandstorethecopiesinanewstackItemsinthenewstackmustbeinthesamepositioninthestackasintheoriginal,Slide13-51,Thestackdestructor,Becausefunctionpopcallsdeleteeachtimeanitemispoppedoffthestack,stackonlyneedstocallpopuntilthestackisemptycharnext;while(!empty()next=pop();,Slide13-52,stackClassImplementation,Thestackclassimplementationisfoundin,Slide13-53,Display13.19(1),Display13.19(2),AQueue,AqueueisadatastructurethatretrievesdatainthesameorderthedatawasstoredIfA,B,andthenCareplacedinaqueue,theywillberemovedintheorderA,B,andthenCAqueueisafirst-in/first-outdatastructurelikethecheckoutlineinasupermarket,Slide13-54,Display13.20,QueueClassImplementation,Thequeueclassisimplementedinamannersimilartothestackexcepttherearetwopointers,onetotrackthefrontofthelist,andonetotrackthebackofthelistInterface:ProgramusingtheQueueClass:Implementation:,Slide13-55,Display13.21(1-2),Display13.22(1-2),Display13.23(1-3),Section13.2Conclusion,CanyouGiveth

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论