




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Chapter3:Lists,Stacks,andQueuesThecommentsforExercise3.4regardingtheamountofabstractnessusedapplyhereTherunningtimeoftheprocedureinFig.3.1isO(厶+P)voidPrintLots(ListL.ListP)intCounter;PositionLpos,Ppos;Lpos=First(L);Ppos=First(P);Counter=1;while(Lpos!=NULL&Ppos!=NULL)if(Ppos-Element=Counter+)printf(%
2、?丄posoElement);Ppos=Next(Ppos.P);Lpos=Next(Lpos,L);)Fig.3.1.(a)Forsinglylinkedlists,thecodeisshowninFig.3.2.- -/*BeforePisthecellbeforethetwoadjacentcellsthataretobeswapped.*/*Errorchecksareomittedforclarity.*/voidSwapWithNext(PositionBeforeP,ListL)PositionP,AfterP;P=BeforeP-Next;AfterP=P-Next;/*Bot
3、hPandAfterPassumednotNULL.*/P-Next=AfterP-Next;BeforeP-Next=AfterP:AfterP-Next=P;)Fig.3.2.Fordoublylinkedlists,thecodeisshowninFig.3.3./*PandAfterParecellstobeswitched.Errorchecksasbefore*/voidSwapWithNext(PositionP.ListL)PositionBeforeP.AfterP;BeforeP=P-Prev;AfterP=P-Next:P-Next=AfterP-Next;BeforeP
4、-Next=AfterP:AfterP-Next=P;P-Next-Prev=P:P-Prev=AfterP;AfterP-Prev=BeforeP:)Fig.33Intersectisshownonpage9.TOC o 1-5 h z/*Thiscodecanbemademoreabstractbyusingoperationssuchas*/*RetrieveandIsPastEndtoreplaceLlPos-ElementandLIPos!=NULL*/*Wehaveavoidedthisbecausetheseoperationswerenotrigorouslydefined*/
5、ListIntersect(ListLI,ListL2)ListResult;PositionLIPos丄2P0S9ResultPos;LIPos=First(LI);L2Pos=First(L2);Result=MakeEmpty(NULL);ResultPos=First(Result);while(LIPos!=NULL&L2Pos!=NULL)if(LlPos-ElementElement)LIPos=Next(LIPos,LI);elseif(LIPos-ElementL2Pos-Element)L2Pos=Next(L2Pos,L2);elseInsert(LlPos-Elemen
6、t.Result,ResultPos):LI=Next(LIPos,LI);L2=Next(L2Pos,L2);ResultPos=Next(ResultPos,Result);returnResult;Fig.3.4containsthecodeforUnion.3.7(a)Onealgorithmistokeeptheresultinasorted(byexponent)linkedlist.EachoftheMNmultipliesrequiresasearchofthelinkedlistforduplicatesSincethesizeofthelinkedlistisO(MN).t
7、hetotalrunningtimeisO(M2N2).Theboundcanbeimprovedbymultiplyingonetermbytheentireotherpolynomial,andthenusingtheequivalentoftheprocedureinExercise3.2toinserttheentiresequence.TheneachsequencetakesO(MN),butthereareonlyMofthem,givingatimeboundofO(M2N).AnO(MNlogMN)solutionispossiblebycomputingallMNpairs
8、andthensortingbyexponentusinganyalgorithminChapter7.ItistheneasytomergeduplicatesafterwardThechoiceofalgorithmdependsontherelativevaluesofMandN.Iftheyareclose,thenthesolutioninpart(c)isbetter.Ifonepolynomialisverysmall,thenthesolutioninpart(b)isbetter.ListUnion(ListLI,ListL2)ListResult;ElementTypeIn
9、sertElement;PositionLIPos丄2Pos,ResultPos;LIPos=First(LI);L2Pos=First(L2);Result=MakeEmpty(NULL);ResultPos=First(Result);while(LIPos!=NULL&L2Pos!=NULL)if(LlPos-ElementElement)InsertElement=LlPos-Element;LIPos=Next(LIPos,LI);elseif(LlPos-ElementL2Pos-Element)InsertElement=L2Pos-Element;L2Pos=Next(L2Po
10、s,L2);elseInsertElement=LlPos-Element;LIPos=Next(LIPos,LI);L2Pos=Next(L2Pos,L2);Insert(InsertElement.Result,ResultPos):ResultPos=Next(ResultPos,Result):/*Flushoutremaininglist*/while(LIPos!=NULL)Insert(LlPos-Element,Result,ResultPos);LIPos=Next(LIPos.LI);ResultPos=Next(ResultPos,Result);while(L2Pos!
11、=NULL)Insert(L2Pos-Element,Result,ResultPos);L2Pos=Next(L2Pos.L2);ResultPos=Next(ResultPos,Result);returnResult;)Fig.343.8OnecanusethePowfunctioninChapter2,adaptedforpolynomialmultiplication.IfPissmaltastandardmethodthatusesO(P)multipliesinsteadofO(logP)mightbebetterbecausethemultiplieswouldinvolvea
12、largenumberwithasmallnumber,whichisgoodforthemultiplicationroutineinpart(b).30ThisisastandardprogrammingprojectThealgorithmcanbespedupbysetting=MmodN,sothatthehotpotatonevergoesaroundthecirclemorethanonce,andthenifMN/2.passingthepotatoappropriatelyinthealternativedirection.Thisrequiresadoublylinkedl
13、ist.Theworst-caserunningtimeisclearlyO(Nmin(M,N),althoughwhentheseheuristicsareused,andMandNarecomparable,thealgorithmmightbesignificantlyfaster.IfA/=1,thealgorithmisclearlylinear.TheVAX/VMSCcompilersmemorymanagementroutinesdopoorlywiththeparticularpatternoffreesinthiscase,causingO(NlogN)behavior.32
14、Reversalofasinglylinkedlistcanbedonenonrecursivelybyusingastack,butthisrequiresO(N)extraspaceThesolutioninFig.3.5issimilartostrategiesemployedingarbagecollectionalgorithms.Atthetopofthewhileloop.thelistfromthestarttoviousPosisalreadyreversed,whereastherestofthelist,fromCurrentPostotheendisnormal.Thi
15、salgorithmusesonlyconstantextraspace/*AssumingnoheaderandLisnotempty.*/ListReverseList(ListL)PositionCurrentPos,NextPosPreviousPos;PreviousPos=NULL;CurrentPos=L;NextPos=L-Next;while(NextPos!=NULL)CurrentPos-Next=PreviousPos;PreviousPos=CurrentPos;CurrentPos=NextPos;NextPos=NextPos-Next;CurrentPos-Ne
16、xt=PreviousPos;returnCurrentPos;)Fig.3.5.35(a)ThecodeisshowninFig.3.6.SeeFig.3.7.Thisfollowsfromwell-knownstatisticaltheorems.SeeSleatorandTaijanspaperintheChapter11references36(c)DeletetakesO(N)andisintwonestedforloopseachofsizeN,givinganobviousO(N)boundAbetterboundofO(N_)isobtainedbynotingthatonly
17、NelementscanbedeletedfromalistofsizeN、henceO(N2)isspentperformingdeletes.TheremainderoftheroutineisO(N2).sotheboundfollowsO(N)/*ArrayimplementatioiLstartingatslot1*/PositionFind(ElementTypeX,ListL)intLWhere;Where=0;for(i=1;i1;i)Li.Element=Li-1.Element;Ll.Element=X;return1:elsereturn0:/*Notfound.*/)F
18、ig.3-6.Sortthelist,andmakeascantoremoveduplicates(whichmustnowbeadjacent).3.17(a)Theadvantagesarethatitissimplertocode,andthereisapossiblesavingsifdeletedkeysaresubsequentlyreinserted(inthesameplace)Thedisadvantageisthatitusesmorespace,becauseeachcellneedsanextrabit(whichistypicallyabyte),andunusedc
19、ellsarenotfreedTwostackscanbeimplementedinanarraybyhavingonegrowfromthelowendofthearrayup,andtheotherfromthehighenddown(a)LetEbeourextendedstack.WewillimplementEwithtwostacksOnestack,whichwellcallS,isusedtokeeptrackofthePushandPopoperations,andtheother.M9keepstrackoftheminimum.ToimplementPiish(X,E),
20、weperformPi(sh(X,S)IfXissmallerthanorequaltothetopelementinstackM.thenwealsoperformPush(X.M).ToimplementPop(E),weperformPop(S).IfXisequaltothetopelementinstackM,thenwealsoPop(M).FindMin(E)isperformedbyexaminingthetopofMAlltheseoperationsareclearly0(1).(b)ThisresultfollowsfromatheoreminChapter7thatsh
21、owsthatsortingmusttakeQ(WlogN)time.O(N)operationsintherepertoire,includingDeleteMin,wouldbesufficienttosort./*Assumingaheader.*/PositionFind(ElementTypeX,ListL)PositionPrevPos,XPos;PrevPos=FindPrevious(X丄);if(PrevPos-Next!=NULL)/*Found.*/XPos=PrevPos-Next:PrevPos-Next=XPos-Next;XPos-Next=L-Next;L-Next=XPos;returnXPos;elsereturnNULL:)Fig.3.7.Threestackscanbeimplementedbyhavingonegrowfromthebottomup.another
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 农民土地承包权转让合同
- 12《富起来到强起来》教学设计、教材分析与教学反思、课前任务单2023-2024学年道德与法治五年级下册统编版
- 3我认识您了 教学设计-2023-2024学年道德与法治一年级上册统编版
- 20《肥皂泡》第一课时 教学设计-2023-2024学年统编版语文三年级下册
- 个人借款中介合同范本
- 2024-2025学年初中生物课后服务活动教学设计:生态系统的平衡与保护
- 矿石洗选加工合同合同范本
- 8的乘法(教学设计)-2024-2025学年二年级上册数学沪教版
- 5《雷雨》节选(教学设计)-2024-2025学年高一语文下学期同步教学教学设计专辑(统编版必修下册)
- 瓷砖合同范本
- 世界主要国际组织课件
- 语言学纲要(新)课件
- 心理评估与诊断简介课件
- 移动式压力容器充装复审换证考试重点题库(180题)
- 小班安全《汤姆走丢了》PPT课件教案反思微视频
- 作物栽培学课件棉花
- 最新小学二年级口算及竖式计算练习题
- 生产与运作管理-陈荣秋
- 金鸡冠的公鸡绘本课件
- 日影朝向及长短
- 沙盘游戏治疗(课堂PPT)
评论
0/150
提交评论