Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
StacksandQueues
Anarrayisarandomaccessdatastructure,whereeachelementcanbeaccesseddirectlyandinconstanttime.Atypicalillustrationofrandomaccessisabookeachpageofthebookcanbeopenindependentlyofothers.Random
accessiscriticaltomanyalgorithms,forexamplebinarysearch.
Alinkedlistisasequentialaccessdatastructure,whereeachelementcanbeaccesedonlyinparticularorder.Atypicalillustrationofsequentialaccessisarollofpaperortapeallpriormaterialmustbeunrolledinordertogetto
datayouwant.
Inthisnoteweconsiderasubcaseofsequentialdatastructures,socalledlimitedaccessdatasturctures.
Stacks
Astackisacontainerofobjectsthatareinsertedandremovedaccordingtothelastinfirstout(LIFO)principle.Inthepushdownstacksonlytwooperationsareallowed:pushtheitem
intothestack,andpoptheitemoutofthestack.Astackisalimitedaccessdatastructureelementscanbeaddedandremovedfromthestackonlyatthetop.pushaddsanitemtothetop
ofthestack,popremovestheitemfromthetop.Ahelpfulanalogyistothinkofastackofbooksyoucanremoveonlythetopbook,alsoyoucanaddanewbookonthetop.
Astackisarecursivedatastructure.HereisastructuraldefinitionofaStack:
astackiseitheremptyor
itconsistesofatopandtherestwhichisastack
Applications
Thesimplestapplicationofastackistoreverseaword.Youpushagivenwordtostackletterbyletterandthenpoplettersfromthestack.
Anotherapplicationisan"undo"mechanismintexteditorsthisoperationisaccomplishedbykeepingalltextchangesinastack.
Backtracking.Thisisaprocesswhenyouneedtoaccessthemostrecentdataelementinaseriesofelements.Thinkofalabyrinthormazehowdoyoufindawayfromanentrancetoanexit?
Onceyoureachadeadend,youmustbacktrack.Butbacktracktowhere?tothepreviouschoicepoint.Therefore,ateachchoicepointyoustoreonastackallpossiblechoices.Then
backtrackingsimplymeanspoppinganextchoicefromthestack.
Languageprocessing:
spaceforparametersandlocalvariablesiscreatedinternallyusingastack.
compiler'ssyntaxcheckformatchingbracesisimplementedbyusingstack.
supportforrecursion
https://www.cs.cmu.edu/~adamchik/15-121/lectures/Stacks%20and%20Queues/Stacks%20and%20Queues.html 1/7
3/3/2017 Stacks and Queues
Implementation
Inthestandardlibraryofclasses,thedatatypestackisanadapterclass,meaningthatastackisbuiltontopofotherdatastructures.Theunderlyingstructureforastackcouldbeanarray,avector,anArrayList,alinkedlist,orany
othercollection.Regardlessofthetypeoftheunderlyingdatastructure,aStackmustimplementthesamefunctionality.Thisisachievedbyprovidingauniqueinterface:
publicinterfaceStackInterface<AnyType>
{
publicvoidpush(AnyTypee)
publicAnyTypepop()
publicAnyTypepeek()
publicbooleanisEmpty()
}
Thefollowingpicturedemonstratestheideaofimplementationbycomposition.
Anotherimplementationrequirement(inadditiontotheaboveinterface)isthatallstackoperationsmustruninconstanttimeO(1).Constanttimemeansthatthereissomeconstantksuchthatanoperationtakesknanosecondsof
computationaltimeregardlessofthestacksize.
Arraybasedimplementation
Inanarraybasedimplementationwemaintainthefollowingfields:anarrayAofadefaultsize(1),thevariabletopthatreferstothetopelementinthestackandthecapacitythat
referstothearraysize.Thevariabletopchangesfrom1tocapacity1.Wesaythatastackisemptywhentop=1,andthestackisfullwhentop=capacity1.
Inafixedsizestackabstraction,thecapacitystaysunchanged,thereforewhentopreachescapacity,thestackobjectthrowsanexception.SeeArrayStack.javaforacomplete
implementationofthestackclass.
Inadynamicstackabstractionwhentopreachescapacity,wedoubleupthestacksize.
https://www.cs.cmu.edu/~adamchik/15-121/lectures/Stacks%20and%20Queues/Stacks%20and%20Queues.html 2/7
3/3/2017 Stacks and Queues
LinkedListbasedimplementation
LinkedListbasedimplementationprovidesthebest(fromtheefficiencypointofview)dynamicstackimplementation.
SeeListStack.javaforacompleteimplementationofthestackclass.
Queues
Aqueueisacontainerofobjects(alinearcollection)thatareinsertedandremovedaccordingtothefirstinfirstout(FIFO)principle.Anexcellentexampleofaqueueisa
lineofstudentsinthefoodcourtoftheUC.Newadditionstoalinemadetothebackofthequeue,whileremoval(orserving)happensinthefront.Inthequeueonlytwo
operationsareallowedenqueueanddequeue.Enqueuemeanstoinsertanitemintothebackofthequeue,dequeuemeansremovingthefrontitem.Thepicture
demonstratestheFIFOaccess.
Thedifferencebetweenstacksandqueuesisinremoving.Inastackweremovetheitemthemostrecentlyaddedinaqueue,weremovetheitemtheleastrecentlyadded.
Implementation
Inthestandardlibraryofclasses,thedatatypequeueisanadapterclass,meaningthataqueueisbuiltontopofotherdatastructures.Theunderlyingstructureforaqueuecouldbeanarray,aVector,anArrayList,aLinkedList,orany
othercollection.Regardlessofthetypeoftheunderlyingdatastructure,aqueuemustimplementthesamefunctionality.Thisisachievedbyprovidingauniqueinterface.
interfaceQueueInterfaceAnyType>
{
publicbooleanisEmpty()
publicAnyTypegetFront()
publicAnyTypedequeue()
https://www.cs.cmu.edu/~adamchik/15-121/lectures/Stacks%20and%20Queues/Stacks%20and%20Queues.html 3/7
3/3/2017 Stacks and Queues
publicvoidenqueue(AnyTypee)
publicvoidclear()
}
EachoftheabovebasicoperationsmustrunatconstanttimeO(1).Thefollowingpicturedemonstratestheideaofimplementationbycomposition.
CircularQueue
GivenanarrayAofadefaultsize(1)withtworeferencesbackandfront,originallysetto1and0respectively.Eachtimeweinsert(enqueue)anewitem,weincreasethebackindexwhenweremove(dequeue)anitemwe
increasethefrontindex.Hereisapicturethatillustratesthemodelafterafewsteps:
Asyouseefromthepicture,thequeuelogicallymovesinthearrayfromlefttoright.Afterseveralmovesbackreachestheend,leavingnospaceforaddingnewelements
https://www.cs.cmu.edu/~adamchik/15-121/lectures/Stacks%20and%20Queues/Stacks%20and%20Queues.html 4/7
3/3/2017 Stacks and Queues
However,thereisafreespacebeforethefrontindex.Weshallusethatspaceforenqueueingnewitems,i.e.thenextentrywillbestoredatindex0,then1,untilfront.Suchamodeliscalledawraparoundqueueoracircularqueue
Finally,whenbackreachesfront,thequeueisfull.Therearetwochoicestohandleafullqueue:a)throwanexceptionb)doublethearraysize.
Thecircularqueueimplementationisdonebyusingthemodulooperator(denoted%),whichiscomputedbytakingtheremainderofdivision(forexample,8%5is3).Byusingthemodulooperator,wecanviewthequeueasa
circulararray,wherethe"wrappedaround"canbesimulatedas"back%array_size".Inadditiontothebackandfrontindexes,wemaintainanotherindex:curforcountingthenumberofelementsinaqueue.Havingthisindex
simplifiesalogicofimplementation.
SeeArrayQueue.javaforacompleteimplementationofacircularqueue.
Applications
ThesimplesttwosearchtechniquesareknownasDepthFirstSearch(DFS)andBreadthFirstSearch(BFS).Thesetwosearchesaredescribedbylookingathowthesearchtree(representingallthepossiblepathsfromthestart)will
betraversed.
DeapthFirstSearchwithaStack
Indepthfirstsearchwegodownapathuntilwegettoadeadendthenwebacktrackorbackup(bypoppingastack)togetanalternativepath.
Createastack
Createanewchoicepoint
Pushthechoicepointontothestack
while(notfoundandstackisnotempty)
Popthestack
Findallpossiblechoicesafterthelastonetried
Pushthesechoicesontothestack
Return
BreadthFirstSearchwithaQueue
Inbreadthfirstsearchweexploreallthenearestpossibilitiesbyfindingallpossiblesuccessorsandenqueuethemtoaqueue.
Createaqueue
Createanewchoicepoint
Enqueuethechoicepointontothequeue
while(notfoundandqueueisnotempty)
Dequeuethequeue
Findallpossiblechoicesafterthelastonetried
Enqueuethesechoicesontothequeue
Return
Wewillseemoreonsearchtechniqueslaterinthecourse.
https://www.cs.cmu.edu/~adamchik/15-121/lectures/Stacks%20and%20Queues/Stacks%20and%20Queues.html 5/7
3/3/2017 Stacks and Queues
ArithmeticExpressionEvaluation
Animportantapplicationofstacksisinparsing.Forexample,acompilermustparsearithmeticexpressionswrittenusinginfixnotation:
1+((2+3)*4+5)*6
Webreaktheproblemofparsinginfixexpressionsintotwostages.First,weconvertfrominfixtoadifferentrepresentationcalledpostfix.Thenweparsethepostfixexpression,whichisasomewhateasierproblemthandirectly
parsinginfix.
ConvertingfromInfixtoPostfix.Typically,wedealwithexpressionsininfixnotation
2+5
wheretheoperators(e.g.+,*)arewrittenbetweentheoperands(e.q,2and5).Writingtheoperatorsaftertheoperandsgivesapostfixexpression2and5arecalledoperands,andthe'+'isoperator.Theabovearithmeticexpressionis
calledinfix,sincetheoperatorisinbetweenoperands.Theexpression
25+
Writingtheoperatorsbeforetheoperandsgivesaprefixexpression
+25
Supposeyouwanttocomputethecostofyourshoppingtrip.Todoso,youaddalistofnumbersandmultiplythembythelocalsalestax(7.25%):
70+150*1.0725
Dependingonthecalculator,theanswerwouldbeeither235.95or230.875.Toavoidthisconfusionweshalluseapostfixnotation
70150+1.0725*
Postfixhasthenicepropertythatparenthesesareunnecessary.
Now,wedescribehowtoconvertfrominfixtopostfix.
1.Readinthetokensoneatatime
2.Ifatokenisaninteger,writeitintotheoutput
3.Ifatokenisanoperator,pushittothestack,ifthestackisempty.Ifthestackisnotempty,youpopentrieswithhigherorequalpriorityandonlythenyoupushthattokentothestack.
4.Ifatokenisaleftparentheses'(',pushittothestack
5.Ifatokenisarightparentheses')',youpopentriesuntilyoumeet'('.
6.Whenyoufinishreadingthestring,youpopupalltokenswhichareleftthere.
7.Arithmeticprecedenceisinincreasingorder:'+','','*','/'
Example.Supposewehaveaninfixexpression:2+(4+3*2+1)/3.Wereadthestringbycharacters.
'2'sendtotheoutput.
'+'pushonthestack.
'('pushonthestack.
'4'sendtotheoutput.
'+'pushonthestack.
https://www.cs.cmu.edu/~adamchik/15-121/lectures/Stacks%20and%20Queues/Stacks%20and%20Queues.html 6/7
3/3/2017 Stacks and Queues
'3'sendtotheoutput.
'*'pushonthestack.
'2'sendtotheoutput.
EvaluatingaPostfixExpression.Wedescribehowtoparseandevaluateapostfixexpression.
1.Wereadthetokensinoneatatime.
2.Ifitisaninteger,pushitonthestack
3.Ifitisabinaryoperator,popthetoptwoelementsfromthestack,applytheoperator,andpushtheresultbackonthestack.
Considerthefollowingpostfixexpression
593+42**7+*
Hereisachainofoperations
StackOperationsOutput
push(5)5
push(9)59
push(3)593
push(pop()+pop())512
push(4)5124
push(2)51242
push(pop()*pop())5128
push(pop()*pop())596
push(7)5967
push(pop()+pop())5103
push(pop()*pop())515
Note,thatdivisionisnotacommutativeoperation,so2/3isnotthesameas3/2.
VictorS.Adamchik,CMU,2009
https://www.cs.cmu.edu/~adamchik/15-121/lectures/Stacks%20and%20Queues/Stacks%20and%20Queues.html 7/7