




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
CollegeofElectronicandInformationEngineeringChongqingUniversityofScienceandTechnologyInstructor:XiongQian
Spring2013DataStructuresandAlgorithms
Chapter3:StacksChapter3Objectives
Uponcompletionyouwillbeableto
Explainthedesign,use,andoperationofastackImplementastackusingalinkedliststructureUnderstandtheoperationofthestackADTWriteapplicationprogramsusingthestackADTDiscussreversingdata,parsing,postponingandbacktrackingStackshighlights3.1BasicStackOperations3.2StackLinkedListImplementation3.3CLanguageImplementations3.4StackADT3.5StackApplicationsStackdefinitionStackofbooksThequestionsare:1.Howtoaddabooktothestack?2.Howtotakethethirdbookfromtop?UnderstandstackYoucanimaginestackasthisbarrelAstackisalastin-firstout
(LIFO)datastructureinwhichallinsertionanddeletionarerestricttooneend,calledtop.PushstackPopstackStacktop3-1
BasicStackOperationsPushstackDATAPUSHDATADATAPushoperationaddsanitematthetopofthestack.Beforeaddingtheitem,thestackspacemustbecheckedtoensurethatthereisenoughroomtoholdtheitem.POPStackPOPDATAPOPremovestheitematthetopofthestackandreturntheitemtotheuser(theapplicationthatcallsthisoperation).Becarefultheemptystateorunderflowstateofthestack,whenyouimplementpopoperation.StacktopStackTopDATAStackTopcopiestheitematthetopofthestackandreturntheitemtotheuser(theapplicationthatcallsthisoperation),butdoesnotremovetheitem.Becarefultheemptystateorunderflowstateofthestack,whenyouimplementstacktopoperation.ExampleofbasicstackoperationsBlueRedGreenPush“Green”BlueRedGreenPush“Blue”RedGreenBluePOPRedGreenBluePUSHRedGreenBlueRedSTACKTOPGreenRedRedPOPGreenRedPOPGreenSeveraldatastructureimplementstack.Linkedlisthassomeadvantagestoimplementstack.dynamicmemoryallocationtechnologytosavememoryspace.easilyidentifytheTopofthestack.theheadoflinkedlist3-2StackLinkedListImplementationConceptualandphysicalstackimplementationsTheStructureof
StackHeadandStacknodeMetadataTopStackDataNextStackHeadstructureStackDatastructurePointertonodestackcounttopendstacknodedatanextendnodeStackAlgorithmsandPseudocodeimplementationCreatestackPushstackPopstackStacktopEmptystackFullstackStackcountDestroystackCreatestackCreatestackjustinitializethemetadataforthestackstructure.?count?Top0count×TopalgorithmcreateStackInitializemetadataforastack.
PreStackisstructureformetadata.Postmetadatainitializedstack.count=0stack.top=nullReturnendcreateStackPushStack0count×TopPUSHGreen1countTopGreendata×nextPUSHGreenInsertsanelementintothestack1.Findmemoryforthenewnode2.Assignthedatatothestacknode3.Changethepointers4.Count+1Insertanodetostackneedstoknowthat:Intoanemptystack?Intoastackwithdata(logicalisthesame)Hasnomemory(overflow)PushStack(Continue)PUSHBlue1countTopGreendata×next2countTopbluedatanextGreendata×nextPUSHBluePushStack(Pseudocode)algorithmpushStack(stack,data)Insert(push)oneitemintothestack.Prestackismetadatastructuretoavalidstack,datacontainsdatatobepushedinstackPostdatahavebeenpushedinstack.Returntrueifsuccessful;falseifmemoryoverflow.1if(stackisfull)1success=falseelse1allocate(newPtr)2newPtr->data=data3newPtr->next=stack.top4stack.top=newPtr5stack.count=stack.count+16success=trueendifreturnsuccessendpushStackPopStack2countTopbluedatanextGreendata×next1countTopGreendata×nextPOPStackPOPStackPopStack(Continue)1countTopGreendata×nextPOPStack0count×TopPOPStackPopStack(pseudocode)AlgorithmpopStack(stack,dataOut)Thisalgorithmpopstheitemonthetopofthestackandreturnsittotheuser.PrestackismetadatastructuretoavalidstackdataOutisareferencevariabletoreceivethedata.PostDatahavebeenreturnedtocallingalgorithm.Returntrueifsuccessful;falseifunderflow.1If(stackempty)1success=false2Else1dltPtr=stack.top2dataOut=stack.top->data3stack.top=stack.top->next4stack.count=stack.count-15recycle(dltPtr)6success=true3endif4returnsuccessendpopstackStackTopThestacktopalgorithmsendsthedataatthetopofthestackbacktothecallingmodulewithoutdeletingthetopnode.Thelogicforthestacktopissimple,butonethingshouldbetakencare,thatisthestateofstackempty.Stacktop(pseudocode)algorithmstackTop(stack,dataOut)ThisalgorithmretrievesthedatafromthetopofthestackwithoutchangingthestackPrestackismetadatastructuretoavalidstackdataOutisareferencevariabletoreceivethedataPostdatahavebeenreturnedtocallingalgorithmReturndatahavebeenreturned,falseifunderflow.1if(stackempty)1success=false2else1DataOut=stack.top->data2Success=true3endif4returnsuccessendstackTopDestroystack(Originalstate)3countTopbluedatanextGreendata×nextReddatanextTempReddatanext3countTopbluedatanextGreendata×nextDestroystack(Deleteitem1)Destroystack(Deleteitem2)3countTopGreendata×nextTempbluedatanextDestroystack(Deleteitem3)0count×TopTempGreendatanextPseudocodeforDestroyStackalgorithmdestroystack(stack)Thisalgorithmreleasesallnodesbacktothedynamicmemory.
Prestackismetadatastructuretoavalidstack
Poststackemptyandallnodesrecycledloop(stack.topnotnull)1temp=stack.top2stack.top=temp.next3recycle(temp)endloopstack.count=0returnenddestroyStackOtherstackalgorithmsFundamentalstackoperationsincludecreatestack,pushstack,popstack,stacktop,anddestroystack.Inordertototallyencapsulatethedataandthedatastructureofthestack.Threesimpleoperationsareintroduced.Theyareemptystack,stackcount,andfullstack.Emptystackoperationisverysimple.Basedonlinkedlistimplementation.Wecanjustchecktheheadnodeofthelisttodeterminewhetherthestackisemptyornot.Thereforethepseudocodeisverysimple.algorithmemptyStack(stack)DetermineswhetherstackisemptyandreturnsaBoolean.PrestackismetadatastructuretoavalidstackPostreturnsstackstatusReturnBoolean,true:stackempty,false:stackcontainsdataif(stack.topnotnull)1result=falseelse1result=trueendifreturnresultEndemptyStackEmptystackOtherconditionstatement(s)thatcanbeusedheretoreplacethisstatement.FullstackalgorithmfullStack(stack)DetermineswhetherstackisfullornotandreturnsaBoolean.
Prestackismetadatastructuretoavalidstack.
Postreturnsstackstatus.
ReturnBoolean,true:stackfull,false:memoryavailableIf(memoryavailable)1result=falseelse1result=trueendifreturnfalseendfullStackStackCountalgorithmstackCount(stack)Returnsthenumberofelementscurrentlyinstack
PrestackismetadatastructuretoavalidstackPostreturnsstackcount
Returnintegercountofnumberofelementsinstack.return(stack.count)endstackCountThereisonlyoneexecutivestatementinthisalgorithm.Ofcourse,itcanbeplacedintheupperfunctionsandeliminatethisalgorithm.ButdonotforgettheessenceofADT—hidingthedataandthestructureabsolutelytotheupperapplications.3-3CLanguageImplementationsThissectionpresentsasimplenon-ADTimplementationofastack.Wedevelopasimpleprogramthatinsertsrandomcharactersintothestackandthenprintsthem.3-4StackADTWebeginthediscussionofthestackADTwithadiscussionofthestackstructureanditsapplicationinterface.Wethendeveloptherequiredfunctions.DataStructureADTImplemenationTypicalstackapplicationscanbeclassifiedintofourbroadcategories:ReversingdataReverseaListConvertdecimaltobinaryParsingdataParseparenthesesPostponingdatausageInfixtopostfixtransformationEvaluatingPostfixexpressionsBacktrackingstepsgoalseekingEightQueensProblem3-5StackApplicationsReverseaListalgorithmreverseNumberThisprogramreversesalistofintegersreadfromthekeyboardbypushingthemintoastackandretrievingthemonebyone.1createStack(stack)2prompt(Enteranumber)3read(number)Fillstack4loop(notendofdataANDnotfullStack(stack))1pushStack(stack,number)2prompt(Enternextnumber:<EOF>tostop)3read(number)5endloopNowprintnumbersinreverse6Loop(notemptyStack(stack))1popStack(stackdataOut)2print(dataOut)7endloopendreverseNumberTheidealiesinreversingdataisveryeasytounderstand.First,pusheachitemonebyoneintostack(statements4-5),thenpopthemoutsuccessively(statements6-7).BecausestackisaLIFOdatastructure,theorderoftheitemhasbeenreversed.(continued)Convertdecimaltobinarydividedecimalnumberby2continuouslyrecordtheremaindersuntilthequotientbecomes0printtheremaindersinbackwardorder.Stackisanidealstructuretoimplementthisprocess.100250225212262321000100112AlgorithmdecimalToBinaryThisalgorithmreadsanintegerfromkeyboardandprintitsbinaryequivalent.Ituseastacktoreversetheorderof0’sand1’sproduce.1createStack(stack)2prompt(Enteradecimalnumbertoconverttobinary)3read(number)4loop(number>0)1digit=numbermodulo22pushOK=push(stack,digit)3if(pushOKfalse)1print(Stackoverflowalert)2quitalgorithm4endif5number=number/25endloopBinarynumbercreatedinstack,nowprintit.6loop(notemptyStack(stack))1popStack(stack,digit)2printdigit7endloop8returnenddecimalToBinaryAlgorithmDecimaltoBinaryThequotientTheremainder:0or1ParsingParsingisanylogicthatbreaksdataintoindependentpiecesforfurtherprocessing.Forexample:totranslateasourceprogramtomachinelanguageUnmatchedParenthesesExampleParenthesesmustbematchedinanalgebraicexpression.
Stackcanholdtheleftpartsofthesesegmentswhilescanninganexpressionorastatementforthelatercomparing.ParseparenthesesAlgorithmparseParensThisalgorithmreadsasourceprogramandparsesittomakesureallopening-closingparenthesesarepaired.1loop(moredata)1read(character)2if(characterisanopeningparenthesis)1pushStack(stack,character)3else1if(characterisclosingparenthesis)1if(emptyStack(stack))1print(Closingparenthesisnotmatchedalert)2else1popStack(stack,token)3endif2endif4endif2endloop3if(notemptyStack(stack))1print(Openingparenthesisnotmatchedalert)4endifendparseParensPostponementdatausagePostponementmeansdeferringdatausageuntilsomelaterpoint(orsomethinghappens).InfixtopostfixtransformationInfix:a+bPrefix:+abPostfix:ab+High-levellanguageusetheinfixconvertittopostfixManualtransformationFullyparenthesizetheexpressionusinganyexplicitparenthesesChangingallinfixnotationsineachparenthesistopostfixnotation,startingfromtheinnermostexpressionsRemoveallparentheses.ExamplesofmanualtransformationA+B*C(A+(B*C))(A+(BC*))(A(BC*)+)ABC*+(A+B)*C+D+E*F-G(((((A+B)*C)+D)+(E*F))-G)(((((AB+)C*)D+)(EF*)+)G-)AB+C*D+EF*+G-TransformexpressionwithstackA*BAB*1.ReadandcopythefirstoperandAtotheresult,weget“A”.2.Readtheoperator“*”andpushitintoastackforlateruse.3.ReadandcopythesecondoperandBtotheresult,wecanget“AB”.4.Finishscanningthesourceexpression,popuptheoperatorandconcatenateittotheresult,weget“AB*”Precedencerulethepriorityofanoperatorpushedintothestackishigherthantheoperatoratthetopofthestack-------pushitintothestack.theoperatoratthetopofthestackhasahigherprioritythanorequaltothecurrentoperator-------itispoppedandplacedintheoutputexpression.A+B*C
ABC*+CopyoperandAtooutputexpression.Pushoperator+intostack.CopyoperandBtooutputexpression.Pushoperator*intostack.(Priorityof*ishigherthan+)CopyoperandCtooutputexpression.Popoperator*andcopytooutputexpression.Popoperator+andcopytooutputexpression.Transformexpressionwithstack
(consideringpriority)A+B*C-D/EABC*+DE/-A+B*C-D/EInfixstackpostfix+B*C-D/EA
B*C-D/E+A*C-D/E+AB
C-D/E*+AB
-D/E*+ABC
D/E-ABC*+/E-ABC*+D
E/-ABC*+D
/-ABC*+DE
ABC*+DE/-Transformexpressionwithstack
(consideringparenthesis)A*(B+C/D)-EABCD/+*E-InfixStackPostfixA*(B+C/D)-E*(B+C/D)-EA(B+C/D)-E*A
B+C/D)-E(*A+C/D)-E(*AB
C/D)-E+(*AB/D)-E+(*ABC
D)-E/+(*ABC)-E/+(*ABCD-E*ABCD/+
E-ABCD/+*
-ABCD/+*E
ABCD/+*E-SummaryoftransforminganinfixtoapostfixexpressionReadeachiteminaninfixexpressionfromlefttorightuntiltotheendoftheinfixexpression1.Iftheitemisanopenparenthesis.2.Iftheitemisacloseparenthesis3.Iftheitemisanoperator4.Iftheitemisanoperand.5.AfterfinishingscanninginfixexpressionTransformingAlgorithmalgorithminToPostFix(formula)convertinfixformulatopostfix.PreFormulaisinfixnotationthathasbeeneditedtoensurethattherearenosyntacticalerrors.Postpostfixformulahasbeenformattedasastringaspostfix.Returnpostfixformula.1createStack(stack)2setpostfixtonullstring3looper=04loop(looper<sizeofformula)1token=formula[looper]//getatoken2if(tokenisopenparenthesis)1pushStack(stacktoken)3elseif(tokeniscloseparenthesis)1popStack(stack,token)2loop(tokenisnotopenparenthesis)1concatenatetokentopostfix2popStack(stack,token)3endloop
4elseif(tokenisoperator)1stackTop(stack,topToken)2loop(notemptyStack(stack)ANDpriority(token)<=priority(topToken))1popStack(stack,tokenOut)2concatenatetokenOuttopostfix3stackTop(stack,topToken)3endloop4pushStack(stack,token)5else1concatenatetokentopostfix6endif7looper=looper+15endloop6loop(notemptyStack(stack))1popStack(stack,token)2concatenatetokentopostfix7endloop8returnpostFixendinToPostFixTransformingAlgorithm(cont.)EvaluatingPostfixexpressionspostfixexpressioneasytoevaluatewithhelpofstack.Whilescanningapostfixexpressionpushalloperandsintoastackforlaterusewhenwemeetanoperator,wecanpopuptwooperandsandevaluatethemwiththeoperatorpushtheresultintothesamestackthefinalresultwillbethelastiteminthestack.2*(4+6)246+*20PosfixStack246+*46+*26+*42642+**1026+4=10
20ExampleofpostfixexpressionevaluationEvaluatingAlgorithmalgorithmpostFixEvaluate(expr)Thisalgorithmevaluatesapostfixexpressionandreturnsitvalue.Preavalidexpression.PostPostfixvaluecomputed.Returnvalueofexpression1exprsize=sizeofexpressionstring2createStack(stack)3index=04loop(index<exprsize)1if(expr[index]isoperand)1pushStack(stack,expr[index])2else1popStack(stack,operand2)2popStack(stack,operand1)3operator=expr[index]4value=calculate(operand1,operator,operand1)5pushStack(stack,value)3endif4index=index+15endloop6popStack(stack,result)7return(result)endpostFixEvaluateBacktrackingBacktrackingiswidelyusedinapplicationsrecordthe“footsteps”choicesat“crossway”tryrepeatedlyuntilyougetyourdestinationorgetthedestinationisunreachable.Stackisanidealstructuretoimplementrecordingandbacktracking“footsteps”and“branchways”asitsLIFOfeature.Thequestionnowiswhattoputintothestack.howtodistinguish“footstep”and“branchway”SimpleExampleofBacktracking(goalseeking)123412567891011131415161718StartnodeB12321B8B954B12321End76B8B954B12321End8B954B12321End1110954B12321Goal161514B171312321(a)(b)(c)(d)(e)(f)SeekgoalalgorithmalgorithmseekGoal(map)Thisalgorithmdeterminesthepathtoadesiredgoal.Preagraphcontainingthepathinitialized.PostPathtothegoalprinted1createStack(stack)2pMap=map.startFindpathandsavepathinstack3loop(pMapnotnullANDgoalNotFound)1if(pMapisgoal)1setgoalNotFoundtofalse2else1pushStack(stack,pMap)2if(pMapisabranchpoint)1loop(morebranchpoints)1createbranchPointnode2pushStack(stack,branchPoint)2endloop3endif4advancetonextnode3endif4endloopPrinttheresult5if(emptyStack(stack))1print(thereisnopathtoyourgoal)6else1print(Thepathtoyourgoalis:)2
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024年遼寧省丹東市振安區(qū)數(shù)學(xué)三年級(jí)第一學(xué)期期末監(jiān)測試題含解析
- 2024年江西省南昌市新建區(qū)三年級(jí)數(shù)學(xué)第一學(xué)期期末考試模擬試題含解析
- 棕色中國風(fēng)從四大發(fā)明說起
- 執(zhí)業(yè)護(hù)士考試科目之間關(guān)系試題及答案
- 行政管理應(yīng)對(duì)變化試題及答案分析
- 2025年行政管理語文考試專題試題及答案
- 行政管理與文化政策試題及答案
- 自考行政管理知識(shí)回顧與試題及答案
- 2025年護(hù)士團(tuán)隊(duì)協(xié)作試題及答案
- 行政管理專業(yè)語文溫習(xí)攻略試題及答案
- 山東省濟(jì)南市重點(diǎn)中學(xué)2025屆高考生物二模試卷含解析
- 湖南省天壹名校聯(lián)盟2025屆高三5月適應(yīng)性考試(物理)
- 新版gmp實(shí)務(wù)教程試題及答案
- 2025年下半年度中鐵特貨物流股份限公司招聘畢業(yè)生三易考易錯(cuò)模擬試題(共500題)試卷后附參考答案
- 2025年中考英語考綱詞匯(包括詞性詞義詞轉(zhuǎn)短語)
- 2025年上海長寧區(qū)高三二模高考英語試卷試題(含答案詳解)
- 2022年全國森林、草原、濕地調(diào)查監(jiān)測技術(shù)規(guī)程-附錄
- 2024年河南省機(jī)關(guān)單位工勤技能人員培訓(xùn)考核高級(jí)工技師《職業(yè)道德》題庫
- 2024年湖南省中考道德與法治試題卷(含答案解析)
- 車輛買賣協(xié)議(簡單通用版)
- 鋼筋調(diào)直機(jī)設(shè)計(jì)
評(píng)論
0/150
提交評(píng)論