SlideShare a Scribd company logo
SSttaacckkss aanndd QQuueeuueess
WWhhaatt iiss aa SSttaacckk?? 
 SSttaacckk iiss aa ddaattaa ssttrruuccttuurree iinn wwhhiicchh ddaattaa iiss 
aaddddeedd aanndd rreemmoovveedd aatt oonnllyy oonnee eenndd ccaalllleedd tthhee 
ttoopp 
 EExxaammpplleess ooff ssttaacckkss aarree:: 
 SSttaacckk ooff bbooookkss 
 SSttaacckk ooff ttrraayyss iinn aa ccaaffeetteerriiaa
SSttaacckk 
 AA LLaasstt IInn FFiirrsstt OOuutt ((LLIIFFOO)) ddaattaa ssttrruuccttuurree 
 PPrriimmaarryy ooppeerraattiioonnss:: PPuusshh aanndd PPoopp 
 PPuusshh 
 AAdddd aann eelleemmeenntt ttoo tthhee ttoopp ooff tthhee ssttaacckk 
 PPoopp 
 RReemmoovvee tthhee eelleemmeenntt ffrroomm tthhee ttoopp ooff tthhee ssttaacckk 
 AAnn eexxaammppllee 
empty stack: initial state 
top 
top A 
top 
top 
push (A) push (B) 
B 
A 
pop 
A
BBuuiillddiinngg SSttaacckk SStteepp--bbyy--SStteepp 
2 
8 
1 
7 
2 
1 
7 
2 
7 
2 
1 
7 
2 
8 
1 
7 
2 
8 
1 
7 
2 
top 
top 
top 
top 
top 
top 
Push(8) Push(2) 
pop() 
pop() pop()
SSttaacckk EErrrroorrss 
 SSttaacckk OOvveerrffllooww 
 AAnn aatttteemmpptt ttoo aadddd aa nneeww eelleemmeenntt iinn aann aallrreeaaddyy ffuullll 
ssttaacckk iiss aann eerrrroorr 
 AA ccoommmmoonn mmiissttaakkee oofftteenn mmaaddee iinn ssttaacckk 
iimmpplleemmeennttaattiioonn 
 SSttaacckk UUnnddeerrffllooww 
 AAnn aatttteemmpptt ttoo rreemmoovvee aann eelleemmeenntt ffrroomm tthhee eemmppttyy 
ssttaacckk iiss aallssoo aann eerrrroorr 
 AAggaaiinn,, aa ccoommmmoonn mmiissttaakkee oofftteenn mmaaddee iinn ssttaacckk 
iimmpplleemmeennttaattiioonn
AApppplliiccaattiioonnss ooff SSttaacckkss 
 SSoommee ddiirreecctt aapppplliiccaattiioonnss:: 
 PPaaggee--vviissiitteedd hhiissttoorryy iinn aa WWeebb bbrroowwsseerr 
 UUnnddoo sseeqquueennccee iinn aa tteexxtt eeddiittoorr 
 EEvvaalluuaattiinngg ppoossttffiixx eexxpprreessssiioonnss ((ee..gg..,, xxyy++)) 
 SSoommee iinnddiirreecctt aapppplliiccaattiioonnss 
 AAuuxxiilliiaarryy ddaattaa ssttrruuccttuurree ffoorr ssoommee aallggoorriitthhmmss ((ee..gg..,, 
DDeepptthh FFiirrsstt SSeeaarrcchh aallggoorriitthhmm)) 
 CCoommppoonneenntt ooff ootthheerr ddaattaa ssttrruuccttuurreess
TThhee SSttaacckk AAbbssttrraacctt DDaattaa TTyyppee 
 SSttaacckkss aarree tthhee ssiimmpplleesstt ooff aallll ddaattaa ssttrruuccttuurreess 
 FFoorrmmaallllyy,, aa ssttaacckk iiss aann aabbssttrraacctt ddaattaa ttyyppee ((AADDTT)) 
tthhaatt ssuuppppoorrttss tthhee ffoolllloowwiinngg ttwwoo mmeetthhooddss:: 
 ppuusshh((ee)):: IInnsseerrtt eelleemmeenntt ee ttoo tthhee ttoopp ooff tthhee ssttaacckk 
 ppoopp(()):: RReemmoovvee ffrroomm tthhee ssttaacckk aanndd rreettuurrnn tthhee ttoopp eelleemmeenntt 
oonn tthhee ssttaacckk;; 
 aann eerrrroorr ooccccuurrss iiff tthhee ssttaacckk iiss eemmppttyy –– wwhhaatt eerrrroorr?? 
 AAddddiittiioonnaallllyy,, lleett uuss aallssoo ddeeffiinnee tthhee ffoolllloowwiinngg 
mmeetthhooddss:: 
 ssiizzee(()):: RReettuurrnn tthhee nnuummbbeerr ooff eelleemmeennttss iinn tthhee ssttaacckk 
 iissEEmmppttyy(()):: RReettuurrnn aa BBoooolleeaann iinnddiiccaattiinngg iiff tthhee ssttaacckk iiss 
eemmppttyy 
 ttoopp(()):: RReettuurrnn tthhee ttoopp eelleemmeenntt iinn tthhee ssttaacckk,, wwiitthhoouutt 
rreemmoovviinngg iitt 
aann eerrrroorr ooccccuurrss iiff tthhee ssttaacckk iiss eemmppttyy
TThhee SSttaacckk AAbbssttrraacctt DDaattaa TTyyppee 
 EExxaammppllee 55..33:: TThhee ffoolllloowwiinngg ttaabbllee sshhoowwss aa sseerriieess ooff ssttaacckk ooppeerraattiioonnss 
aanndd tthheeiirr eeffffeeccttss oonn aann iinniittiiaallllyy eemmppttyy ssttaacckk SS ooff iinntteeggeerrss.. 
OOppeerraattiioonn OOuuttppuutt SSttaacckk CCoonntteennttss 
ppuusshh((55)) 
ppuusshh((33)) 
ppoopp(()) 
ppuusshh((77)) 
ppoopp(()) 
ttoopp(()) 
ppoopp(()) 
ppoopp(()) 
iissEEmmppttyy(()) 
ppuusshh((99)) 
ppuusshh((77)) 
ppuusshh((33)) 
ppuusshh((55)) 
ssiizzee(()) 
ppoopp(()) 
ppuusshh((88)) 
ppoopp(()) 
ppoopp(()) 
-- 
-- 
33- 
- 
77 
55 
55 
""eerrrroorr““ 
ttrruuee 
-- 
-- 
-- 
-- 
44 
55- 
- 
88 
33 
((55)) 
((55,, 33)) 
((55)) 
((55,, 77)) 
((55)) 
((55)) 
(()) 
(()) 
(()) 
((99)) 
((99,, 77)) 
((99,, 77,, 33)) 
((99,, 77,, 33,, 55)) 
((99,, 77,, 33,, 55)) 
((99,, 77,, 33)) 
((99,, 77,, 33,, 88)) 
((99,, 77,, 33)) 
((99,, 77))
AA SSttaacckk IInntteerrffaaccee iinn JJaavvaa 
 TThhee ssttaacckk ddaattaa ssttrruuccttuurree iiss iinncclluuddeedd aass aa ""bbuuiilltt-- 
iinn"" ccllaassss iinn tthhee jjaavvaa..uuttiill ppaacckkaaggee ooff JJaavvaa.. 
 CCllaassss jjaavvaa..uuttiill..SSttaacckk iiss aa ddaattaa ssttrruuccttuurree tthhaatt 
ssttoorreess ggeenneerriicc JJaavvaa oobbjjeeccttss aanndd iinncclluuddeess,,aammoonngg 
ootthheerrss,, tthhee ffoolllloowwiinngg mmeetthhooddss:: 
 ppuusshh(()),, 
 ppoopp(()) 
 ppeeeekk(()) ((eeqquuiivvaalleenntt ttoo ttoopp(()))),, 
 ssiizzee(()),, aanndd eemmppttyy(()) ((eeqquuiivvaalleenntt ttoo iissEEmmppttyy(()))).. 
MMeetthhooddss ppoopp(()) aanndd ppeeeekk(()) tthhrrooww eexxcceeppttiioonn 
EEmmppttyySSttaacckkEExxcceeppttiioonn iiff tthheeyy aarree ccaalllleedd oonn aann eemmppttyy 
ssttaacckk..
TThhee SSttaacckk AAbbssttrraacctt DDaattaa TTyyppee 
 IImmpplleemmeennttiinngg aann aabbssttrraacctt ddaattaa ttyyppee iinn JJaavvaa iinnvvoollvveess ttwwoo 
sstteeppss.. TThhee ffiirrsstt sstteepp iiss tthhee ddeeffiinniittiioonn ooff aa JJaavvaa AApppplliiccaattiioonn 
PPrrooggrraammmmiinngg IInntteerrffaaccee ((AAPPII)),, oorr ssiimmppllyy iinntteerrffaaccee,, wwhhiicchh 
ddeessccrriibbeess tthhee nnaammeess ooff tthhee mmeetthhooddss tthhaatt tthhee AADDTT ssuuppppoorrttss 
aanndd hhooww tthheeyy aarree ttoo bbee ddeeccllaarreedd aanndd uusseedd.. 
 IInn aaddddiittiioonn,, wwee mmuusstt ddeeffiinnee eexxcceeppttiioonnss ffoorr aannyy eerrrroorr 
ccoonnddiittiioonnss tthhaatt ccaann aarriissee.. FFoorr iinnssttaannccee,, tthhee eerrrroorr ccoonnddiittiioonn 
tthhaatt ooccccuurrss wwhheenn ccaalllliinngg mmeetthhoodd ppoopp(()) oorr ttoopp(()) oonn aann eemmppttyy 
ssttaacckk iiss ssiiggnnaalleedd bbyy tthhrroowwiinngg aann eexxcceeppttiioonn ooff ttyyppee 
EEmmppttyySSttaacckkEExxcceeppttiioonn,,
TThhee SSttaacckk AAbbssttrraacctt DDaattaa TTyyppee 
CCooddee FFrraaggmmeenntt 55..22:: IInntteerrffaaccee SSttaacckk ddooccuummeenntteedd wwiitthh ccoommmmeennttss iinn JJaavvaaddoocc ssttyyllee ((SSeeccttiioonn 11..99..33)).. 
NNoottee aallssoo tthhee uussee ooff tthhee ggeenneerriicc ppaarraammeetteerriizzeedd ttyyppee,, EE,, wwhhiicchh iimmpplliieess tthhaatt aa ssttaacckk ccaann ccoonnttaaiinn 
eelleemmeennttss ooff aannyy ssppeecciiffiieedd ccllaassss..
AA SSiimmppllee AArrrraayy--BBaasseedd SSttaacckk IImmpplleemmeennttaattiioonn 
 WWee ccaann iimmpplleemmeenntt aa ssttaacckk bbyy ssttoorriinngg iittss eelleemmeennttss iinn aann 
aarrrraayy.. 
 SSppeecciiffiiccaallllyy,, tthhee ssttaacckk iinn tthhiiss iimmpplleemmeennttaattiioonn ccoonnssiissttss ooff 
 aann NN--eelleemmeenntt aarrrraayy SS 
 pplluuss aann iinntteeggeerr vvaarriiaabbllee tt tthhaatt ggiivveess tthhee iinnddeexx ooff tthhee ttoopp eelleemmeenntt iinn aarrrraayy SS.. 
FFiigguurree 55..22:: IImmpplleemmeennttiinngg aa ssttaacckk wwiitthh aann aarrrraayy SS.. TThhee ttoopp eelleemmeenntt iinn tthhee ssttaacckk iiss ssttoorreedd iinn tthhee cceellll SS[[tt]].. 
 RReeccaalllliinngg tthhaatt aarrrraayyss ssttaarrtt aatt iinnddeexx 00 iinn JJaavvaa,, 
 wwee iinniittiiaalliizzee tt ttoo −−11,, aanndd wwee uussee tthhiiss vvaalluuee ffoorr tt ttoo iiddeennttiiffyy aann eemmppttyy 
ssttaacckk.. 
 LLiikkeewwiissee,, wwee ccaann uussee tt ttoo ddeetteerrmmiinnee tthhee nnuummbbeerr ooff eelleemmeennttss 
((tt ++ 11)).. 
 FFuullllSSttaacckkEExxcceeppttiioonn,, ttoo ssiiggnnaall tthhee eerrrroorr tthhaatt aarriisseess iiff wwee ttrryy ttoo 
iinnsseerrtt aa nneeww eelleemmeenntt iinnttoo aa ffuullll aarrrraayy.. 
 EExxcceeppttiioonn FFuullllSSttaacckkEExxcceeppttiioonn iiss ssppeecciiffiicc ttoo tthhiiss 
iimmpplleemmeennttaattiioonn aanndd iiss nnoott ddeeffiinneedd iinn tthhee ssttaacckk AADDTT..
CCooddee FFrraaggmmeenntt 55..33:: IImmpplleemmeennttiinngg aa 
ssttaacckk uussiinngg aann aarrrraayy ooff aa ggiivveenn ssiizzee,, NN..
Analyzing tthhee AArrrraayy--BBaasseedd SSttaacckk 
IImmpplleemmeennttaattiioonn 
 TThhee ccoorrrreeccttnneessss ooff tthhee mmeetthhooddss iinn tthhee aarrrraayy--bbaasseedd iimmpplleemmeennttaattiioonn ffoolllloowwss 
iimmmmeeddiiaatteellyy ffrroomm tthhee ddeeffiinniittiioonn ooff tthhee mmeetthhooddss tthheemmsseellvveess.. 
 NNoottee tthhaatt wwee ccoouulldd hhaavvee aavvooiiddeedd rreesseettttiinngg tthhee oolldd SS[[tt]] ttoo nnuullll aanndd wwee wwoouulldd ssttiillll 
hhaavvee aa ccoorrrreecctt mmeetthhoodd.. 
 TThheerree iiss aa ttrraaddee--ooffff iinn bbeeiinngg aabbllee ttoo aavvooiidd tthhiiss aassssiiggnnmmeenntt sshhoouulldd wwee bbee tthhiinnkkiinngg 
aabboouutt iimmpplleemmeennttiinngg tthheessee aallggoorriitthhmmss iinn JJaavvaa.. 
 TThhee ttrraaddee--ooffff iinnvvoollvveess tthhee JJaavvaa ggaarrbbaaggee ccoolllleeccttiioonn mmeecchhaanniissmm tthhaatt sseeaarrcchheess 
mmeemmoorryy ffoorr oobbjjeeccttss tthhaatt aarree nnoo lloonnggeerr rreeffeerreenncceedd bbyy aaccttiivvee oobbjjeeccttss,, aanndd rreeccllaaiimmss 
tthheeiirr ssppaaccee ffoorr ffuuttuurree uussee.. LLeett ee == SS[[tt]] bbee tthhee ttoopp eelleemmeenntt bbeeffoorree tthhee ppoopp mmeetthhoodd 
iiss ccaalllleedd.. 
 BByy mmaakkiinngg SS[[tt]] aa nnuullll rreeffeerreennccee,, wwee iinnddiiccaattee tthhaatt tthhee ssttaacckk nnoo lloonnggeerr nneeeeddss ttoo hhoolldd 
aa rreeffeerreennccee ttoo oobbjjeecctt ee.. IInnddeeeedd,, iiff tthheerree aarree nnoo ootthheerr aaccttiivvee rreeffeerreenncceess ttoo ee,, tthheenn 
tthhee mmeemmoorryy ssppaaccee ttaakkeenn bbyy ee wwiillll bbee rreeccllaaiimmeedd bbyy tthhee ggaarrbbaaggee ccoolllleeccttoorr.. 
 TTaabbllee 55..11 sshhoowwss tthhee rruunnnniinngg ttiimmeess ffoorr mmeetthhooddss iinn aa rreeaalliizzaattiioonn ooff aa ssttaacckk bbyy aann 
aarrrraayy.. EEaacchh ooff tthhee ssttaacckk mmeetthhooddss iinn tthhee aarrrraayy rreeaalliizzaattiioonn eexxeeccuutteess aa ccoonnssttaanntt 
nnuummbbeerr ooff ssttaatteemmeennttss iinnvvoollvviinngg aarriitthhmmeettiicc ooppeerraattiioonnss,, ccoommppaarriissoonnss,, aanndd 
aassssiiggnnmmeennttss.. 
 IInn aaddddiittiioonn,, ppoopp aallssoo ccaallllss iissEEmmppttyy,, wwhhiicchh iittsseellff rruunnss iinn ccoonnssttaanntt ttiimmee.. TThhuuss,, iinn tthhiiss 
iimmpplleemmeennttaattiioonn ooff tthhee SSttaacckk AADDTT,, eeaacchh mmeetthhoodd rruunnss iinn ccoonnssttaanntt ttiimmee,, tthhaatt iiss,, tthheeyy 
eeaacchh rruunn iinn OO((11)) ttiimmee..
 TTaabbllee 55..11:: PPeerrffoorrmmaannccee ooff aa ssttaacckk rreeaalliizzeedd bbyy aann aarrrraayy.. TThhee ssppaaccee 
uussaaggee iiss OO((NN)),, wwhheerree NN iiss tthhee ssiizzee ooff tthhee aarrrraayy,, ddeetteerrmmiinneedd aatt tthhee ttiimmee tthhee 
ssttaacckk iiss iinnssttaannttiiaatteedd.. NNoottee tthhaatt tthhee ssppaaccee uussaaggee iiss iinnddeeppeennddeenntt ffrroomm tthhee 
nnuummbbeerr nn ≤≤ NN ooff eelleemmeennttss tthhaatt aarree aaccttuuaallllyy iinn tthhee ssttaacckk.. 
MMeetthhoodd TTiimmee 
ssiizzee OO((11)) 
iiss EEmmppttyy OO((11)) 
ttoopp OO((11)) 
ppuusshh OO((11)) 
ppoopp OO((11))
A Drawback wwiitthh tthhee AArrrraayy--BBaasseedd 
SSttaacckk IImmpplleemmeennttaattiioonn 
 The array implementation of a stack is simple and efficient. 
 This implementation has one negative aspect 
 it must assume a fixed upper bound, CAPACITY, on the ultimate size of the stack. 
 In Code Fragment 5.4, we chose the capacity value 1,000 more or less arbitrarily. 
 An application may actually need much less space than this, 
 which would waste memory. 
 An application may need more space than this, 
 which would cause our stack implementation to generate an exception as soon as a client 
program tries to push its 1,001st object on the stack. 
 Thus, even with its simplicity and efficiency, the array-based stack implementation is 
not necessarily ideal. 
 Fortunately, there is another implementation, which we discuss next, 
 that does not have a size limitation 
 and use space proportional to the actual number of elements stored in the stack. 
 Still, in cases where we have a good estimate on the number of items needing to go 
in the stack, 
 the array-based implementation is hard to beat. 
 Stacks serve a vital role in a number of computing applications, so it is helpful to have a fast 
stack ADT implementation such as the simple array-based implementation.
Implementing aa SSttaacckk wwiitthh aa 
GGeenneerriicc LLiinnkkeedd LLiisstt 
 UUssiinngg aa ssiinnggllyy lliinnkkeedd lliisstt ttoo iimmpplleemmeenntt tthhee ssttaacckk AADDTT.. 
 IInn ddeessiiggnniinngg ssuucchh aann iimmpplleemmeennttaattiioonn,, wwee nneeeedd ttoo ddeecciiddee iiff 
 tthhee ttoopp ooff tthhee ssttaacckk iiss aatt tthhee hheeaadd 
 oorr aatt tthhee ttaaiill ooff tthhee lliisstt.. 
 SSiinnccee wwee ccaann iinnsseerrtt aanndd ddeelleettee eelleemmeennttss iinn ccoonnssttaanntt ttiimmee oonnllyy aatt tthhee 
hheeaadd.. 
 TThhuuss,, iitt iiss mmoorree eeffffiicciieenntt ttoo hhaavvee tthhee ttoopp ooff tthhee ssttaacckk aatt tthhee hheeaadd ooff oouurr 
lliisstt.. 
 iinn oorrddeerr ttoo ppeerrffoorrmm ooppeerraattiioonn ssiizzee iinn ccoonnssttaanntt ttiimmee,, 
 wwee kkeeeepp ttrraacckk ooff tthhee ccuurrrreenntt nnuummbbeerr ooff eelleemmeennttss iinn aann iinnssttaannccee vvaarriiaabbllee.. 
 RRaatthheerr tthhaann uussee aa lliinnkkeedd lliisstt tthhaatt ccaann oonnllyy ssttoorree oobbjjeeccttss ooff aa cceerrttaaiinn 
ttyyppee,, wwee wwoouulldd lliikkee,, iinn tthhiiss ccaassee,, ttoo iimmpplleemmeenntt aa ggeenneerriicc ssttaacckk uussiinngg 
aa ggeenneerriicc lliinnkkeedd lliisstt.. 
 TThhuuss,, wwee nneeeedd ttoo uussee aa ggeenneerriicc kkiinndd ooff nnooddee ttoo iimmpplleemmeenntt tthhiiss 
lliinnkkeedd lliisstt.. WWee sshhooww ssuucchh aa NNooddee ccllaassss iinn CCooddee FFrraaggmmeenntt 55..6..
Implementing aa SSttaacckk wwiitthh aa 
GGeenneerriicc LLiinnkkeedd LLiisstt 
 CCooddee FFrraaggmmeenntt 55..6:: CCllaassss NNooddee,, wwhhiicchh iimmpplleemmeennttss aa ggeenneerriicc nnooddee ffoorr aa 
ssiinnggllyy lliinnkkeedd lliisstt.. 

AA GGeenneerriicc NNooddeeSSttaacckk CCllaassss 
 AA JJaavvaa iimmpplleemmeennttaattiioonn ooff aa ssttaacckk,, bbyy mmeeaannss ooff aa ggeenneerriicc ssiinnggllyy lliinnkkeedd lliisstt,, iiss 
ggiivveenn iinn CCooddee FFrraaggmmeenntt 55..77.. 
 AAllll tthhee mmeetthhooddss ooff tthhee SSttaacckk iinntteerrffaaccee aarree eexxeeccuutteedd iinn ccoonnssttaanntt ttiimmee.. 
 IInn aaddddiittiioonn ttoo bbeeiinngg ttiimmee eeffffiicciieenntt,, tthhiiss lliinnkkeedd lliisstt iimmpplleemmeennttaattiioonn hhaass aa 
ssppaaccee rreeqquuiirreemmeenntt tthhaatt iiss OO((nn)),, wwhheerree nn iiss tthhee ccuurrrreenntt nnuummbbeerr ooff eelleemmeennttss 
iinn tthhee ssttaacckk.. 
 TThhuuss,, tthhiiss iimmpplleemmeennttaattiioonn ddooeess nnoott rreeqquuiirree tthhaatt aa nneeww eexxcceeppttiioonn bbee ccrreeaatteedd 
ttoo hhaannddllee ssiizzee oovveerrffllooww pprroobblleemmss.. WWee uussee aann iinnssttaannccee vvaarriiaabbllee ttoopp ttoo rreeffeerr 
ttoo tthhee hheeaadd ooff tthhee lliisstt ((wwhhiicchh ppooiinnttss ttoo tthhee nnuullll oobbjjeecctt iiff tthhee lliisstt iiss eemmppttyy)).. 
 WWhheenn wwee ppuusshh aa nneeww eelleemmeenntt ee oonn tthhee ssttaacckk,, wwee ssiimmppllyy ccrreeaattee aa nneeww nnooddee 
vv ffoorr ee,, rreeffeerreennccee ee ffrroomm vv,, aanndd iinnsseerrtt vv aatt tthhee hheeaadd ooff tthhee lliisstt.. 
 LLiikkeewwiissee,, wwhheenn wwee ppoopp aann eelleemmeenntt ffrroomm tthhee ssttaacckk,, wwee ssiimmppllyy rreemmoovvee tthhee 
nnooddee aatt tthhee hheeaadd ooff tthhee lliisstt aanndd rreettuurrnn iittss eelleemmeenntt.. TThhuuss,, wwee ppeerrffoorrmm aallll 
iinnsseerrttiioonnss aanndd rreemmoovvaallss ooff eelleemmeennttss aatt tthhee hheeaadd ooff tthhee lliisstt..
Code Fragment 5.7: Class NodeStack, which implements the Stack 
interface using a singly linked list, whose nodes are objects of class Node from 
Code Fragment 5.6.
Reversing aann AArrrraayy UUssiinngg aa SSttaacckk 
 WWee ccaann uussee aa ssttaacckk ttoo rreevveerrssee tthhee eelleemmeennttss iinn aann aarrrraayy,, 
 tthheerreebbyy pprroodduucciinngg aa nnoonnrreeccuurrssiivvee aallggoorriitthhmm ffoorr tthhee aarrrraayy--rreevveerrssaall pprroobblleemm 
iinnttrroodduucceedd iinn SSeeccttiioonn 33..55..11.. 
 TThhee bbaassiicc iiddeeaa iiss ssiimmppllyy ttoo ppuusshh aallll tthhee eelleemmeennttss ooff tthhee aarrrraayy iinn oorrddeerr iinnttoo aa 
ssttaacckk aanndd tthheenn ffiillll tthhee aarrrraayy bbaacckk uupp aaggaaiinn bbyy ppooppppiinngg tthhee eelleemmeennttss ooffff ooff 
tthhee ssttaacckk.. 
 IInn CCooddee FFrraaggmmeenntt 55..88,, wwee ggiivvee aa JJaavvaa iimmpplleemmeennttaattiioonn ooff tthhiiss aallggoorriitthhmm.. 
IInncciiddeennttaallllyy,, tthhiiss mmeetthhoodd aallssoo iilllluussttrraatteess hhooww wwee ccaann uussee ggeenneerriicc ttyyppeess iinn aa 
ssiimmppllee aapppplliiccaattiioonn tthhaatt uusseess aa ggeenneerriicc ssttaacckk.. 
 IInn ppaarrttiiccuullaarr,, wwhheenn tthhee eelleemmeennttss aarree ppooppppeedd ooffff tthhee ssttaacckk iinn tthhiiss eexxaammppllee,, 
tthheeyy aarree aauuttoommaattiiccaallllyy rreettuurrnneedd aass eelleemmeennttss ooff tthhee EE ttyyppee;; hheennccee,, tthheeyy ccaann 
bbee iimmmmeeddiiaatteellyy rreettuurrnneedd ttoo tthhee iinnppuutt aarrrraayy.. WWee sshhooww aann eexxaammppllee uussee ooff tthhiiss 
mmeetthhoodd iinn CCooddee FFrraaggmmeenntt 55..99..
Code Fragment 5.8: A generic method that reverses the elements in an 
array of type E objects, using a stack declared using the Stack<E> interface.
Code Fragment 5.9: A test of the reverse method using two arrays.
Code Fragment 5.8: A generic method that reverses the elements in an 
array of type E objects, using a stack declared using the Stack<E> interface.
Code Fragment 5.9: A test of the reverse method using two arrays.
MMaattcchhiinngg PPaarreenntthheesseess aanndd HHTTMMLL TTaaggss 
 TTwwoo rreellaatteedd aapppplliiccaattiioonnss ooff ssttaacckkss,, 
 tthhee ffiirrsstt ooff wwhhiicchh iiss ffoorr mmaattcchhiinngg ppaarreenntthheesseess 
 aanndd ggrroouuppiinngg ssyymmbboollss iinn aarriitthhmmeettiicc eexxpprreessssiioonnss.. 
 AArriitthhmmeettiicc eexxpprreessssiioonnss ccaann ccoonnttaaiinn vvaarriioouuss ppaaiirrss ooff 
ggrroouuppiinngg ssyymmbboollss,, ssuucchh aass 
•• PPaarreenntthheesseess:: ""(("" aanndd ""))"" 
•• BBrraacceess:: ""{{"" aanndd ""}}"" 
•• BBrraacckkeettss:: ""[["" aanndd ""]]"" 
•• FFlloooorr ffuunnccttiioonn ssyymmbboollss:: "" ⌊⌊"" aanndd ""⌋⌋"" 
•• CCeeiilliinngg ffuunnccttiioonn ssyymmbboollss:: ""⌈⌈"" aanndd ""⌉⌉,,"" 
 aanndd eeaacchh ooppeenniinngg ssyymmbbooll mmuusstt mmaattcchh wwiitthh iittss 
ccoorrrreessppoonnddiinngg cclloossiinngg ssyymmbbooll.. :: 
 [[((55 ++ xx)) −− ((yy ++ zz))]]..
MMaattcchhiinngg PPaarreenntthheesseess aanndd HHTTMMLL TTaaggss 
TThhee ffoolllloowwiinngg eexxaammpplleess ffuurrtthheerr iilllluussttrraattee 
tthhiiss ccoonncceepptt:: 
•• CCoorrrreecctt:: (( ))(((( )))){{(([[(( ))]]))}} 
•• CCoorrrreecctt:: (((((( ))(((( )))){{(([[(( ))]]))}})))) 
•• IInnccoorrrreecctt:: ))(((( )))){{(([[(( ))]]))}} 
•• IInnccoorrrreecctt:: (({{[[]]))}} 
•• IInnccoorrrreecctt:: ((..
AAnn AAllggoorriitthhmm ffoorr PPaarreenntthheesseess MMaattcchhiinngg 
 AAnn iimmppoorrttaanntt pprroobblleemm iinn pprroocceessssiinngg aarriitthhmmeettiicc eexxpprreessssiioonnss iiss ttoo mmaakkee ssuurree tthheeiirr 
ggrroouuppiinngg ssyymmbboollss mmaattcchh uupp ccoorrrreeccttllyy.. 
 WWee ccaann uussee aa ssttaacckk SS ttoo ppeerrffoorrmm tthhee mmaattcchhiinngg ooff ggrroouuppiinngg ssyymmbboollss iinn aann aarriitthhmmeettiicc 
eexxpprreessssiioonn wwiitthh aa ssiinnggllee lleefftt--ttoo--rriigghhtt ssccaann.. 
 TThhee aallggoorriitthhmm tteessttss tthhaatt lleefftt aanndd rriigghhtt ssyymmbboollss mmaattcchh uupp aanndd aallssoo tthhaatt tthhee lleefftt aanndd 
rriigghhtt ssyymmbboollss aarree bbootthh ooff tthhee ssaammee ttyyppee.. 
 SSuuppppoossee wwee aarree ggiivveenn aa sseeqquueennccee XX == xx00xx11xx22……xxnn−−11,, wwhheerree eeaacchh xxii iiss aa ttookkeenn tthhaatt 
ccaann bbee aa ggrroouuppiinngg ssyymmbbooll,, aa vvaarriiaabbllee nnaammee,, aann aarriitthhmmeettiicc ooppeerraattoorr,, oorr aa nnuummbbeerr.. 
 TThhee bbaassiicc iiddeeaa bbeehhiinndd cchheecckkiinngg tthhaatt tthhee ggrroouuppiinngg ssyymmbboollss iinn SS mmaattcchh ccoorrrreeccttllyy,, 
 iiss ttoo pprroocceessss tthhee ttookkeennss iinn XX iinn oorrddeerr.. 
 EEaacchh ttiimmee wwee eennccoouunntteerr aann ooppeenniinngg ssyymmbbooll,, wwee ppuusshh tthhaatt ssyymmbbooll oonnttoo SS,, 
 aanndd eeaacchh ttiimmee wwee eennccoouunntteerr aa cclloossiinngg ssyymmbbooll,, wwee ppoopp tthhee ttoopp ssyymmbbooll ffrroomm tthhee ssttaacckk SS 
((aassssuummiinngg SS iiss nnoott eemmppttyy)) aanndd wwee cchheecckk tthhaatt tthheessee ttwwoo ssyymmbboollss aarree ooff tthhee ssaammee ttyyppee.. 
 IIff tthhee ssttaacckk iiss eemmppttyy aafftteerr wwee hhaavvee pprroocceesssseedd tthhee wwhhoollee sseeqquueennccee,, tthheenn tthhee ssyymmbboollss iinn XX 
mmaattcchh.. 
 AAssssuummiinngg tthhaatt tthhee ppuusshh aanndd ppoopp ooppeerraattiioonnss aarree iimmpplleemmeenntteedd ttoo rruunn iinn ccoonnssttaanntt ttiimmee,, tthhiiss 
aallggoorriitthhmm rruunnss iinn OO((nn)),, tthhaatt iiss lliinneeaarr,, ttiimmee.. WWee ggiivvee aa ppsseeuuddoo--ccooddee ddeessccrriippttiioonn ooff tthhiiss 
aallggoorriitthhmm iinn CCooddee FFrraaggmmeenntt 55..1100..
Code Fragment 5.10: Algorithm for matching grouping symbols in an 
arithmetic expression.
MMaattcchhiinngg TTaaggss iinn aann HHTTMMLL DDooccuummeenntt 
 AAnnootthheerr aapppplliiccaattiioonn iinn wwhhiicchh mmaattcchhiinngg iiss iimmppoorrttaanntt iiss iinn tthhee 
vvaalliiddaattiioonn ooff HHTTMMLL ddooccuummeennttss.. 
 HHTTMMLL iiss tthhee ssttaannddaarrdd ffoorrmmaatt ffoorr hhyyppeerrlliinnkkeedd ddooccuummeennttss oonn tthhee 
IInntteerrnneett.. II 
 nn aann HHTTMMLL ddooccuummeenntt,, ppoorrttiioonnss ooff tteexxtt aarree ddeelliimmiitteedd bbyy HHTTMMLL ttaaggss.. 
 AA ssiimmppllee ooppeenniinngg HHTTMMLL ttaagg hhaass tthhee ffoorrmm "<<nnaammee>>" aanndd tthhee 
ccoorrrreessppoonnddiinngg cclloossiinngg ttaagg hhaass tthhee ffoorrmm "<<//nnaammee>>.." CCoommmmoonnllyy uusseedd 
HHTTMMLL ttaaggss iinncclluuddee 
•• bbooddyy:: ddooccuummeenntt bbooddyy 
•• hh11:: sseeccttiioonn hheeaaddeerr 
•• cceenntteerr:: cceenntteerr jjuussttiiffyy 
•• pp:: ppaarraaggrraapphh 
•• ooll:: nnuummbbeerreedd ((oorrddeerreedd)) lliisstt 
•• llii:: lliisstt iitteemm.. 
 WWee sshhooww aa ssaammppllee HHTTMMLL ddooccuummeenntt aanndd aa ppoossssiibbllee rreennddeerriinngg iinn 
FFiigguurree 55..33..
Figure 5.3: Illustrating HTML tags. (a) An HTML document; (b) its rendering.
Code Fragment 5.11: A complete Java program for testing if an HTML 
document has fully matching tags. (Continues in Code Fragment 5.12.)
WWhhaatt iiss QQuueeuuee?? 
 QQuueeuuee iiss aa ddaattaa ssttrruuccttuurree iinn wwhhiicchh iinnsseerrttiioonn iiss 
ddoonnee aatt oonnee eenndd ((FFrroonntt)),, wwhhiillee ddeelleettiioonn iiss 
ppeerrffoorrmmeedd aatt tthhee ootthheerr eenndd ((RReeaarr)) 
 CCoonnttrraasstt wwiitthh ssttaacckk,, wwhheerree iinnsseerrttiioonn aanndd ddeelleettiioonn 
aatt oonnee aanndd tthhee ssaammee eenndd 
 IItt iiss FFiirrsstt IInn,, FFiirrsstt OOuutt ((FFIIFFOO)) ssttrruuccttuurree 
 FFoorr eexxaammppllee,, ccuussttoommeerrss ssttaannddiinngg iinn aa cchheecckk--oouutt 
lliinnee iinn aa ssttoorree,, tthhee ffiirrsstt ccuussttoommeerr iinn iiss tthhee ffiirrsstt 
ccuussttoommeerr sseerrvveedd..
QQuueeuuee ooppeerraattiioonnss 
 EEnnqquueeuuee:: iinnsseerrtt aann eelleemmeenntt aatt tthhee rreeaarr ooff tthhee 
lliisstt 
 DDeeqquueeuuee:: ddeelleettee tthhee eelleemmeenntt aatt tthhee ffrroonntt ooff 
tthhee lliisstt 
Insert 
(Enqueue) 
Remove 
(Dequeue) front rear
BBuuiillddiinngg aa QQuueeuuee SStteepp--bbyy--SStteepp 
 TThheerree aarree sseevveerraall ddiiffffeerreenntt aallggoorriitthhmmss ttoo 
iimmpplleemmeenntt EEnnqquueeuuee aanndd DDeeqquueeuuee 
 EEnnqquueeuuiinngg 
 TThhee ffrroonntt iinnddeexx iiss aallwwaayyss ffiixxeedd 
 TThhee rreeaarr iinnddeexx mmoovveess ffoorrwwaarrdd iinn tthhee aarrrraayy 
rear 
3 
front 
Enqueue(3) 
3 6 
front 
rear 
Enqueue(6) 
3 6 9 
front 
rear 
Enqueue(9)
BBuuiillddiinngg aa QQuueeuuee SStteepp--bbyy--SStteepp 
 DDeeqquueeuuiinngg 
 TThhee eelleemmeenntt aatt tthhee ffrroonntt ooff tthhee qquueeuuee iiss rreemmoovveedd 
 MMoovvee aallll tthhee eelleemmeennttss aafftteerr iitt bbyy oonnee ppoossiittiioonn 
6 9 
front 
rear 
Dequeue() 
rear 
9 
front 
rear = -1 
front 
Dequeue() Dequeue()
TThhee QQuueeuuee AAbbssttrraacctt DDaattaa TTyyppee 
 FFoorrmmaallllyy,, tthhee qquueeuuee aabbssttrraacctt ddaattaa ttyyppee ddeeffiinneess aa ccoolllleeccttiioonn tthhaatt kkeeeeppss 
oobbjjeeccttss iinn aa sseeqquueennccee,, wwhheerree 
 eelleemmeenntt aacccceessss aanndd ddeelleettiioonn aarree rreessttrriicctteedd ttoo tthhee ffiirrsstt eelleemmeenntt iinn tthhee sseeqquueennccee,, 
tthhee ffrroonntt ooff tthhee qquueeuuee,, 
 aanndd eelleemmeenntt iinnsseerrttiioonn iiss rreessttrriicctteedd ttoo tthhee eenndd ooff tthhee sseeqquueennccee,, tthhee rreeaarr ooff tthhee 
qquueeuuee.. 
 TThhiiss rreessttrriiccttiioonn eennffoorrcceess tthhee rruullee tthhaatt iitteemmss aarree iinnsseerrtteedd aanndd ddeelleetteedd iinn aa qquueeuuee 
aaccccoorrddiinngg ttoo tthhee ffiirrsstt--iinn ffiirrsstt--oouutt ((FFIIFFOO)) pprriinncciippllee.. 
 TThhee qquueeuuee aabbssttrraacctt ddaattaa ttyyppee ((AADDTT)) ssuuppppoorrttss tthhee ffoolllloowwiinngg ttwwoo ffuunnddaammeennttaall 
mmeetthhooddss:: 
 eennqquueeuuee((ee)):: IInnsseerrtt eelleemmeenntt ee aatt tthhee rreeaarr ooff tthhee qquueeuuee.. 
 ddeeqquueeuuee(()):: RReemmoovvee aanndd rreettuurrnn ffrroomm tthhee qquueeuuee tthhee oobbjjeecctt aatt tthhee ffrroonntt;; 
 aann eerrrroorr ooccccuurrss iiff tthhee qquueeuuee iiss eemmppttyy.. 
 AAddddiittiioonnaallllyy,, ssiimmiillaarr ttoo tthhee ccaassee wwiitthh tthhee SSttaacckk AADDTT,, tthhee qquueeuuee AADDTT iinncclluuddeess 
tthhee ffoolllloowwiinngg ssuuppppoorrttiinngg mmeetthhooddss:: 
 ssiizzee(()):: RReettuurrnn tthhee nnuummbbeerr ooff oobbjjeeccttss iinn tthhee qquueeuuee.. 
 iissEEmmppttyy(()):: RReettuurrnn aa BBoooolleeaann vvaalluuee tthhaatt iinnddiiccaatteess wwhheetthheerr tthhee qquueeuuee iiss eemmppttyy.. 
 ffrroonntt(()):: RReettuurrnn,, bbuutt ddoo nnoott rreemmoovvee,, tthhee ffrroonntt oobbjjeecctt iinn tthhee qquueeuuee;; 
 aann eerrrroorr ooccccuurrss iiff tthhee qquueeuuee iiss eemmppttyy..
TThhee QQuueeuuee AAbbssttrraacctt DDaattaa TTyyppee 
 EExxaammppllee 55..44:: TThhee 
ffoolllloowwiinngg ttaabbllee sshhoowwss aa 
sseerriieess ooff qquueeuuee 
ooppeerraattiioonnss aanndd tthheeiirr 
eeffffeeccttss oonn aann iinniittiiaallllyy 
eemmppttyy qquueeuuee QQ ooff iinntteeggeerr 
oobbjjeeccttss.. FFoorr ssiimmpplliicciittyy,, wwee 
uussee iinntteeggeerrss iinnsstteeaadd ooff 
iinntteeggeerr oobbjjeeccttss aass 
aarrgguummeennttss ooff tthhee 
ooppeerraattiioonnss.. 
OOppeerraattiioonn OOuuttppuutt ffrroonntt ←← QQ ←← rreeaarr 
eennqquueeuuee((55)) 
eennqquueeuuee((33)) 
ddeeqquueeuuee(( )) 
eennqquueeuuee((77)) 
ddeeqquueeuuee(( )) 
ffrroonntt(( )) 
ddeeqquueeuuee(( )) 
ddeeqquueeuuee(( )) 
iissEEmmppttyy(( )) 
eennqquueeuuee((99)) 
eennqquueeuuee((77)) 
ssiizzee(()) 
eennqquueeuuee((33)) 
eennqquueeuuee((55)) 
ddeeqquueeuuee(( )) 
-- 
-- 
55 
-- 
33 
77 
77 
"eerrrroorr" 
ttrruuee 
-- 
-- 
22 
-- 
-- 
99 
((55)) 
((55,, 33)) 
((33)) 
((33,, 77)) 
((77)) 
((77)) 
(( )) 
(( )) 
(( )) 
((99)) 
((99,, 77)) 
((99,, 77)) 
((99,, 77,, 33)) 
((99,, 77,, 33,, 55)) 
((77,, 33,, 55))
TThhee QQuueeuuee AAbbssttrraacctt DDaattaa TTyyppee 
 EExxaammppllee AApppplliiccaattiioonnss 
 TThheerree aarree sseevveerraall ppoossssiibbllee aapppplliiccaattiioonnss ffoorr qquueeuueess.. 
 SSttoorreess,, 
 tthheeaatteerrss,, 
 rreesseerrvvaattiioonn cceenntteerrss,, 
 aanndd ootthheerr ssiimmiillaarr sseerrvviicceess ttyyppiiccaallllyy pprroocceessss ccuussttoommeerr rreeqquueessttss 
aaccccoorrddiinngg ttoo tthhee FFIIFFOO pprriinncciippllee.. 
 AA qquueeuuee wwoouulldd tthheerreeffoorree bbee aa llooggiiccaall cchhooiiccee ffoorr aa ddaattaa 
ssttrruuccttuurree ttoo hhaannddllee ttrraannssaaccttiioonn pprroocceessssiinngg ffoorr ssuucchh 
aapppplliiccaattiioonnss.. 
 FFoorr eexxaammppllee,, iitt wwoouulldd bbee aa nnaattuurraall cchhooiiccee ffoorr hhaannddlliinngg 
ccaallllss ttoo tthhee rreesseerrvvaattiioonn cceenntteerr ooff aann aaiirrlliinnee oorr ttoo tthhee bbooxx 
ooffffiiccee ooff aa tthheeaatteerr..
AA QQuueeuuee IInntteerrffaaccee iinn JJaavvaa 
 AA JJaavvaa iinntteerrffaaccee ffoorr tthhee qquueeuuee AADDTT iiss ggiivveenn iinn CCooddee 
FFrraaggmmeenntt 55..1133.. 
 TThhiiss ggeenneerriicc iinntteerrffaaccee ssppeecciiffiieess tthhaatt oobbjjeeccttss ooff aarrbbiittrraarryy 
oobbjjeecctt ttyyppeess ccaann bbee iinnsseerrtteedd iinnttoo tthhee qquueeuuee.. 
 TThhuuss,, wwee ddoonn''tt hhaavvee ttoo uussee eexxpplliicciitt ccaassttiinngg wwhheenn 
rreemmoovviinngg eelleemmeennttss.. 
 NNoottee tthhaatt tthhee ssiizzee aanndd iissEEmmppttyy mmeetthhooddss hhaavvee tthhee ssaammee 
mmeeaanniinngg aass tthheeiirr ccoouunntteerrppaarrttss iinn tthhee SSttaacckk AADDTT.. 
 TThheessee ttwwoo mmeetthhooddss,, aass wweellll aass tthhee ffrroonntt mmeetthhoodd,, aarree 
kknnoowwnn aass aacccceessssoorr mmeetthhooddss,, ffoorr tthheeyy rreettuurrnn aa vvaalluuee aanndd 
ddoo nnoott cchhaannggee tthhee ccoonntteennttss ooff tthhee ddaattaa ssttrruuccttuurree..
Code Fragment 5.13: Interface Queue documented with comments 
in Javadoc style.
A Simple AArrrraayy--BBaasseedd QQuueeuuee IImmpplleemmeennttaattiioonn 
 WWee pprreesseenntt aa ssiimmppllee rreeaalliizzaattiioonn ooff aa qquueeuuee bbyy mmeeaannss ooff 
aann aarrrraayy,, QQ,, ooff ffiixxeedd ccaappaacciittyy,, ssttoorriinngg iittss eelleemmeennttss.. 
 SSiinnccee tthhee mmaaiinn rruullee wwiitthh tthhee qquueeuuee AADDTT iiss tthhaatt wwee iinnsseerrtt 
aanndd ddeelleettee oobbjjeeccttss aaccccoorrddiinngg ttoo tthhee FFIIFFOO pprriinncciippllee,, wwee 
mmuusstt ddeecciiddee hhooww wwee aarree ggooiinngg ttoo kkeeeepp ttrraacckk ooff tthhee ffrroonntt 
aanndd rreeaarr ooff tthhee qquueeuuee.. 
 OOnnee ppoossssiibbiilliittyy iiss ttoo aaddaapptt tthhee aapppprrooaacchh wwee uusseedd ffoorr tthhee 
ssttaacckk iimmpplleemmeennttaattiioonn,, 
 lleettttiinngg QQ[[00]] bbee tthhee ffrroonntt ooff tthhee qquueeuuee aanndd tthheenn lleettttiinngg tthhee qquueeuuee 
ggrrooww ffrroomm tthheerree.. 
 TThhiiss iiss nnoott aann eeffffiicciieenntt ssoolluuttiioonn,, hhoowweevveerr,, ffoorr iitt rreeqquuiirreess tthhaatt wwee 
mmoovvee aallll tthhee eelleemmeennttss ffoorrwwaarrdd oonnee aarrrraayy cceellll eeaacchh ttiimmee wwee ppeerrffoorrmm 
aa ddeeqquueeuuee ooppeerraattiioonn.. 
 SSuucchh aann iimmpplleemmeennttaattiioonn wwoouulldd tthheerreeffoorree ttaakkee OO((nn)) ttiimmee ttoo ppeerrffoorrmm 
tthhee ddeeqquueeuuee mmeetthhoodd,, wwhheerree nn iiss tthhee ccuurrrreenntt nnuummbbeerr ooff oobbjjeeccttss iinn 
tthhee qquueeuuee.. 
 IIff wwee wwaanntt ttoo aacchhiieevvee ccoonnssttaanntt ttiimmee ffoorr eeaacchh qquueeuuee mmeetthhoodd,, wwee 
nneeeedd aa ddiiffffeerreenntt aapppprrooaacchh,, bbuutt tthhaatt aapppprrooaacchh mmaayy hhaavvee iittss oowwnn 
ddeemmeerriittss..
Using an Array iinn aa CCiirrccuullaarr WWaayy 
 TToo aavvooiidd mmoovviinngg oobbjjeeccttss oonnccee tthheeyy aarree ppllaacceedd iinn QQ,, 
 wwee ddeeffiinnee ttwwoo vvaarriiaabblleess ff aanndd rr,, wwhhiicchh hhaavvee tthhee ffoolllloowwiinngg mmeeaanniinnggss:: 
 ff iiss aann iinnddeexx ttoo tthhee cceellll ooff QQ ssttoorriinngg tthhee ffiirrsstt eelleemmeenntt ooff tthhee qquueeuuee ((nneexxtt ccaannddiiddaattee ttoo bbee rreemmoovveedd bbyy aa ddeeqquueeuuee 
ooppeerraattiioonn)),, 
 ff == rr qquueeuuee iiss eemmppttyy.. 
 rr iiss aann iinnddeexx ttoo tthhee nneexxtt aavvaaiillaabbllee aarrrraayy cceellll iinn QQ.. 
 IInniittiiaallllyy,, wwee aassssiiggnn ff == rr == 00,, wwhhiicchh iinnddiiccaatteess tthhaatt tthhee qquueeuuee iiss eemmppttyy.. 
 WWhheenn wwee rreemmoovvee aann eelleemmeenntt ffrroomm tthhee ffrroonntt ooff tthhee qquueeuuee,, iinnccrreemmeenntt ff ttoo iinnddeexx 
tthhee nneexxtt cceellll.. 
 AAddddiinngg aann eelleemmeenntt,, wwee ssttoorree iitt iinn cceellll QQ[[rr]] aanndd iinnccrreemmeenntt rr ttoo iinnddeexx tthhee nneexxtt 
aavvaaiillaabbllee cceellll iinn QQ.. 
 TThhiiss sscchheemmee aalllloowwss uuss ttoo iimmpplleemmeenntt mmeetthhooddss ffrroonntt,, eennqquueeuuee,, aanndd ddeeqquueeuuee iinn 
ccoonnssttaanntt ttiimmee,, tthhaatt iiss,, OO((11)) ttiimmee.. 
 HHoowweevveerr,, tthheerree iiss ssttiillll aa pprroobblleemm wwiitthh tthhiiss aapppprrooaacchh.. 
 what happens if we repeatedly enqueue and dequeue a single element N 
different times. 
 WWee wwoouulldd hhaavvee ff == rr == NN.. IIff wwee wweerree tthheenn ttoo ttrryy ttoo iinnsseerrtt tthhee eelleemmeenntt jjuusstt oonnee mmoorree 
ttiimmee,, wwee wwoouulldd ggeett aann aarrrraayy--oouutt--ooff--bboouunnddss eerrrroorr ((ssiinnccee tthhee NN vvaalliidd llooccaattiioonnss iinn QQ aarree 
ffrroomm QQ[[00]] ttoo QQ[[NN −− 11]])),, eevveenn tthhoouugghh tthheerree iiss pplleennttyy ooff rroooomm iinn tthhee qquueeuuee iinn tthhiiss ccaassee.. 
 TToo aavvooiidd tthhiiss pprroobblleemm aanndd bbee aabbllee ttoo uuttiilliizzee aallll ooff tthhee aarrrraayy QQ,, wwee lleett tthhee ff aanndd rr 
iinnddiicceess ""wwrraapp aarroouunndd"" tthhee eenndd ooff QQ.. 
 TThhaatt iiss,, wwee nnooww vviieeww QQ aass aa ""cciirrccuullaarr aarrrraayy"" tthhaatt ggooeess ffrroomm QQ[[00]] ttoo QQ[[NN −− 11]] aanndd tthheenn 
iimmmmeeddiiaatteellyy bbaacckk ttoo QQ[[00]] aaggaaiinn.. ((SSeeee FFiigguurree 55..44..))
Figure 5.4: Using array Q in a circular fashion: 
(a) the "normal" configuration with f ≤ r; (b) the "wrapped around" configuration 
(b) with r < f. The cells storing queue elements are highlighted.
Using tthhee MMoodduulloo OOppeerraattoorr ttoo 
IImmpplleemmeenntt aa CCiirrccuullaarr AArrrraayy 
 IImmpplleemmeennttiinngg tthhiiss cciirrccuullaarr vviieeww ooff QQ iiss aaccttuuaallllyy pprreettttyy eeaassyy.. 
 EEaacchh ttiimmee wwee iinnccrreemmeenntt ff oorr rr,, wwee ccoommppuuttee tthhiiss iinnccrreemmeenntt aass 
""((ff ++ 11)) mmoodd NN"" oorr ""((rr ++ 11)) mmoodd NN,,"" rreessppeeccttiivveellyy.. 
 ""mmoodd"" iiss tthhee mmoodduulloo ooppeerraattoorr,, wwhhiicchh iiss ccoommppuutteedd bbyy ttaakkiinngg 
tthhee rreemmaaiinnddeerr aafftteerr aann iinntteeggrraall ddiivviissiioonn.. 
 FFoorr eexxaammppllee,, 1144 ddiivviiddeedd bbyy 44 iiss 33 wwiitthh rreemmaaiinnddeerr 22,, ssoo 1144 
mmoodd 44 == 22.. 
 JJaavvaa uusseess ""%%"" ttoo ddeennoottee tthhee mmoodduulloo ooppeerraattoorr.. BByy uussiinngg tthhee 
mmoodduulloo ooppeerraattoorr,, wwee ccaann vviieeww QQ aass aa cciirrccuullaarr aarrrraayy aanndd 
iimmpplleemmeenntt eeaacchh qquueeuuee mmeetthhoodd iinn aa ccoonnssttaanntt aammoouunntt ooff ttiimmee 
((tthhaatt iiss,, OO((11)) ttiimmee)).. WWee ddeessccrriibbee hhooww ttoo uussee tthhiiss aapppprrooaacchh ttoo 
iimmpplleemmeenntt aa qquueeuuee iinn CCooddee FFrraaggmmeenntt 55..1144..
Code Fragment 5.14: Implementation of a queue using a circular array. 
The implementation uses the modulo operator to "wrap" indices around the end of the 
array and it also includes two instance variables, f and r, which index the front of the 
queue and first empty cell after the rear of the queue respectively.
Using tthhee MMoodduulloo OOppeerraattoorr ttoo 
IImmpplleemmeenntt aa CCiirrccuullaarr AArrrraayy 
 TThhee iimmpplleemmeennttaattiioonn aabboovvee ccoonnttaaiinnss aann iimmppoorrttaanntt ddeettaaiill,, wwhhiicchh mmiigghhtt bbee mmiisssseedd aatt ffiirrsstt.. 
 CCoonnssiiddeerr tthhee ssiittuuaattiioonn tthhaatt ooccccuurrss iiff wwee eennqquueeuuee NN oobbjjeeccttss iinnttoo QQ wwiitthhoouutt ddeeqquueeuuiinngg aannyy 
ooff tthheemm.. WWee wwoouulldd hhaavvee ff == rr,, wwhhiicchh iiss tthhee ssaammee ccoonnddiittiioonn tthhaatt ooccccuurrss wwhheenn tthhee qquueeuuee iiss 
eemmppttyy.. 
 HHeennccee,, wwee wwoouulldd nnoott bbee aabbllee ttoo tteellll tthhee ddiiffffeerreennccee bbeettwweeeenn aa ffuullll qquueeuuee aanndd aann eemmppttyy oonnee 
iinn tthhiiss ccaassee.. 
 FFoorrttuunnaatteellyy,, tthhiiss iiss nnoott aa bbiigg pprroobblleemm,, aanndd aa nnuummbbeerr ooff wwaayyss ffoorr ddeeaalliinngg wwiitthh iitt eexxiisstt.. 
 TThhee ssoolluuttiioonn wwee ddeessccrriibbee hheerree iiss ttoo iinnssiisstt tthhaatt QQ ccaann nneevveerr hhoolldd mmoorree tthhaann NN −− 11 oobbjjeeccttss.. 
 TThhiiss ssiimmppllee rruullee ffoorr hhaannddlliinngg aa ffuullll qquueeuuee ttaakkeess ccaarree ooff tthhee ffiinnaall pprroobblleemm wwiitthh oouurr 
iimmpplleemmeennttaattiioonn,, aanndd lleeaaddss ttoo tthhee ppsseeuuddoo--ccooddeedd ddeessccrriippttiioonnss ooff tthhee qquueeuuee mmeetthhooddss ggiivveenn 
iinn CCooddee FFrraaggmmeenntt 55..1144.. 
 NNoottee oouurr iinnttrroodduuccttiioonn ooff aann iimmpplleemmeennttaattiioonn--ssppeecciiffiicc eexxcceeppttiioonn,, ccaalllleedd FFuullllQQuueeuueeEExxcceeppttiioonn,, 
ttoo ssiiggnnaall tthhaatt nnoo mmoorree eelleemmeennttss ccaann bbee iinnsseerrtteedd iinn tthhee qquueeuuee.. 
 AAllssoo nnoottee tthhee wwaayy wwee ccoommppuuttee tthhee ssiizzee ooff tthhee qquueeuuee bbyy mmeeaannss ooff tthhee eexxpprreessssiioonn ((NN −− ff ++ 
rr)) mmoodd NN,, wwhhiicchh ggiivveess tthhee ccoorrrreecctt rreessuulltt bbootthh iinn tthhee ""nnoorrmmaall"" ccoonnffiigguurraattiioonn ((wwhheenn ff ≤≤ rr)) aanndd 
iinn tthhee ""wwrraappppeedd aarroouunndd"" ccoonnffiigguurraattiioonn ((wwhheenn rr << ff)).. 
 TThhee JJaavvaa iimmpplleemmeennttaattiioonn ooff aa qquueeuuee bbyy mmeeaannss ooff aann aarrrraayy iiss ssiimmiillaarr ttoo tthhaatt ooff aa ssttaacckk,, aanndd 
iiss lleefftt aass aann eexxeerrcciissee ((PP--55..44)).. 
 TTaabbllee 55..22 sshhoowwss tthhee rruunnnniinngg ttiimmeess ooff mmeetthhooddss iinn aa rreeaalliizzaattiioonn ooff aa qquueeuuee bbyy aann aarrrraayy.. AAss 
wwiitthh oouurr aarrrraayy--bbaasseedd ssttaacckk iimmpplleemmeennttaattiioonn,, eeaacchh ooff tthhee qquueeuuee mmeetthhooddss iinn tthhee aarrrraayy 
rreeaalliizzaattiioonn eexxeeccuutteess aa ccoonnssttaanntt nnuummbbeerr ooff ssttaatteemmeennttss iinnvvoollvviinngg aarriitthhmmeettiicc ooppeerraattiioonnss,, 
ccoommppaarriissoonnss,, aanndd aassssiiggnnmmeennttss.. TThhuuss,, eeaacchh mmeetthhoodd iinn tthhiiss iimmpplleemmeennttaattiioonn rruunnss iinn OO((11)) 
ttiimmee..
TTaabbllee 55..22:: PPeerrffoorrmmaannccee ooff aa qquueeuuee rreeaalliizzeedd bbyy aann aarrrraayy 
 TThhee ssppaaccee uussaaggee iiss OO((NN)),, 
wwhheerree NN iiss tthhee ssiizzee ooff tthhee 
aarrrraayy,, ddeetteerrmmiinneedd aatt tthhee 
ttiimmee tthhee qquueeuuee iiss ccrreeaatteedd.. 
NNoottee tthhaatt tthhee ssppaaccee 
uussaaggee iiss iinnddeeppeennddeenntt 
ffrroomm tthhee nnuummbbeerr nn << NN ooff 
eelleemmeennttss tthhaatt aarree aaccttuuaallllyy 
iinn tthhee qquueeuuee.. 
MMeetthhoodd TTiimmee 
SSiizzee 
iissEEmmppttyy 
ffrroonntt 
eennqquueeuuee 
ddeeqquueeuuee 
OO((11)) 
OO((11)) 
OO((11)) 
OO((11)) 
OO((11)) 
Problem is the capacity of the queue to be some fixed value. In a real 
application, we may actually need more or less queue capacity than this, but if 
we have a good capacity estimate, then the array-based implementation is quite 
efficient.
Implementing aa QQuueeuuee wwiitthh aa 
GGeenneerriicc LLiinnkkeedd LLiisstt 
WWee ccaann eeffffiicciieennttllyy iimmpplleemmeenntt tthhee qquueeuuee AADDTT 
uussiinngg aa ggeenneerriicc ssiinnggllyy lliinnkkeedd lliisstt.. 
 FFoorr eeffffiicciieennccyy rreeaassoonnss,, 
 tthhee ffrroonntt ooff tthhee qquueeuuee ttoo bbee aatt tthhee hheeaadd ooff tthhee lliisstt,, 
 aanndd tthhee rreeaarr ooff tthhee qquueeuuee ttoo bbee aatt tthhee ttaaiill ooff tthhee lliisstt.. 
 IInn tthhiiss wwaayy,, wwee rreemmoovvee ffrroomm tthhee hheeaadd aanndd iinnsseerrtt aatt 
tthhee ttaaiill.. ((WWhhyy wwoouulldd iitt bbee bbaadd ttoo iinnsseerrtt aatt tthhee hheeaadd aanndd 
rreemmoovvee aatt tthhee ttaaiill??)) NNoottee tthhaatt wwee nneeeedd ttoo mmaaiinnttaaiinn 
rreeffeerreenncceess ttoo bbootthh tthhee hheeaadd aanndd ttaaiill nnooddeess ooff tthhee lliisstt.. 
RRaatthheerr tthhaann ggoo iinnttoo eevveerryy ddeettaaiill ooff tthhiiss 
iimmpplleemmeennttaattiioonn,, wwee ssiimmppllyy ggiivvee aa JJaavvaa 
iimmpplleemmeennttaattiioonn ffoorr tthhee ffuunnddaammeennttaall qquueeuuee mmeetthhooddss iinn 
CCooddee FFrraaggmmeenntt 55..1155..
CCooddee FFrraaggmmeenntt 55..1155:: MMeetthhooddss eennqquueeuuee aanndd ddeeqquueeuuee iinn tthhee 
iimmpplleemmeennttaattiioonn ooff tthhee qquueeuuee AADDTT bbyy mmeeaannss ooff aa ssiinnggllyy lliinnkkeedd lliisstt,, uussiinngg 
nnooddeess ffrroomm ccllaassss NNooddee ooff CCooddee FFrraaggmmeenntt 55..66.. 
Each of the methods of the singly linked list implementation of the queue ADT runs in 
O(1) time. We also avoid the need to specify a maximum size for the queue, but this 
benefit comes at the expense of increasing the amount of space used per element. 
Still, the methods in the singly linked list queue implementation are more complicated 
than we might like, for we must take extra care in how we deal with special cases 
where the queue is empty before an enqueue or where the queue becomes empty 
after a dequeue.
RRoouunndd RRoobbiinn SScchheedduulleerrss 
 AA ppooppuullaarr uussee ooff tthhee qquueeuuee ddaattaa ssttrruuccttuurree iiss ttoo iimmpplleemmeenntt 
aa rroouunndd rroobbiinn sscchheedduulleerr,, wwhheerree 
 wwee iitteerraattee tthhrroouugghh aa ccoolllleeccttiioonn ooff eelleemmeennttss iinn aa cciirrccuullaarr ffaasshhiioonn 
aanndd ""sseerrvviiccee"" eeaacchh eelleemmeenntt bbyy ppeerrffoorrmmiinngg aa ggiivveenn aaccttiioonn oonn iitt.. 
 SSuucchh aa sscchheedduullee iiss uusseedd,, 
 ffoorr eexxaammppllee,, ttoo ffaaiirrllyy aallllooccaattee aa rreessoouurrccee tthhaatt mmuusstt bbee sshhaarreedd bbyy aa 
ccoolllleeccttiioonn ooff cclliieennttss.. 
 FFoorr iinnssttaannccee,, wwee ccaann uussee aa rroouunndd rroobbiinn sscchheedduulleerr ttoo aallllooccaattee aa sslliiccee 
ooff CCPPUU ttiimmee ttoo vvaarriioouuss aapppplliiccaattiioonnss rruunnnniinngg ccoonnccuurrrreennttllyy oonn aa 
ccoommppuutteerr.. 
 WWee ccaann iimmpplleemmeenntt aa rroouunndd rroobbiinn sscchheedduulleerr uussiinngg aa 
qquueeuuee,, QQ,, bbyy rreeppeeaatteeddllyy ppeerrffoorrmmiinngg tthhee ffoolllloowwiinngg sstteeppss 
((sseeee FFiigguurree 55..55)):: 
11.. ee ←← QQ..ddeeqquueeuuee(()) 
22.. SSeerrvviiccee eelleemmeenntt ee 
33.. QQ..eennqquueeuuee((ee))
Figure 5.5: The three iterative steps for using a queue to implement a round robin 
scheduler.
TThhee JJoosseepphhuuss PPrroobblleemm 
 IInn tthhee cchhiillddrreenn''ss ggaammee ""hhoott ppoottaattoo,,"" aa ggrroouupp ooff nn cchhiillddrreenn 
ssiitt iinn aa cciirrccllee ppaassssiinngg aann oobbjjeecctt,, ccaalllleedd tthhee ""ppoottaattoo,,"" 
aarroouunndd tthhee cciirrccllee.. TThhee ppoottaattoo bbeeggiinnss wwiitthh aa ssttaarrttiinngg cchhiilldd 
iinn tthhee cciirrccllee,, aanndd tthhee cchhiillddrreenn ccoonnttiinnuuee ppaassssiinngg tthhee ppoottaattoo 
uunnttiill aa lleeaaddeerr rriinnggss aa bbeellll,, aatt wwhhiicchh ppooiinntt tthhee cchhiilldd hhoollddiinngg 
tthhee ppoottaattoo mmuusstt lleeaavvee tthhee ggaammee aafftteerr hhaannddiinngg tthhee ppoottaattoo 
ttoo tthhee nneexxtt cchhiilldd iinn tthhee cciirrccllee.. AAfftteerr tthhee sseelleecctteedd cchhiilldd 
lleeaavveess,, tthhee ootthheerr cchhiillddrreenn cclloossee uupp tthhee cciirrccllee.. TThhiiss 
pprroocceessss iiss tthheenn ccoonnttiinnuueedd uunnttiill tthheerree iiss oonnllyy oonnee cchhiilldd 
rreemmaaiinniinngg,, wwhhoo iiss ddeeccllaarreedd tthhee wwiinnnneerr.. IIff tthhee lleeaaddeerr 
aallwwaayyss uusseess tthhee ssttrraatteeggyy ooff rriinnggiinngg tthhee bbeellll aafftteerr tthhee 
ppoottaattoo hhaass bbeeeenn ppaasssseedd kk ttiimmeess,, ffoorr ssoommee ffiixxeedd vvaalluuee kk,, 
tthheenn ddeetteerrmmiinniinngg tthhee wwiinnnneerr ffoorr aa ggiivveenn lliisstt ooff cchhiillddrreenn iiss 
kknnoowwnn aass tthhee JJoosseepphhuuss pprroobblleemm..
Solving tthhee JJoosseepphhuuss PPrroobblleemm 
UUssiinngg aa QQuueeuuee 
 WWee ccaann ssoollvvee tthhee JJoosseepphhuuss pprroobblleemm ffoorr aa ccoolllleeccttiioonn ooff nn 
eelleemmeennttss uussiinngg aa qquueeuuee,, bbyy aassssoocciiaattiinngg tthhee ppoottaattoo wwiitthh 
tthhee eelleemmeenntt aatt tthhee ffrroonntt ooff tthhee qquueeuuee aanndd ssttoorriinngg 
eelleemmeennttss iinn tthhee qquueeuuee aaccccoorrddiinngg ttoo tthheeiirr oorrddeerr aarroouunndd 
tthhee cciirrccllee.. TThhuuss,, ppaassssiinngg tthhee ppoottaattoo iiss eeqquuiivvaalleenntt ttoo 
ddeeqquueeuuiinngg aann eelleemmeenntt aanndd iimmmmeeddiiaatteellyy eennqquueeuuiinngg iitt 
aaggaaiinn.. AAfftteerr tthhiiss pprroocceessss hhaass bbeeeenn ppeerrffoorrmmeedd kk ttiimmeess,, wwee 
rreemmoovvee tthhee ffrroonntt eelleemmeenntt bbyy ddeeqquueeuuiinngg iitt ffrroomm tthhee qquueeuuee 
aanndd ddiissccaarrddiinngg iitt.. WWee sshhooww aa ccoommpplleettee JJaavvaa pprrooggrraamm ffoorr 
ssoollvviinngg tthhee JJoosseepphhuuss pprroobblleemm uussiinngg tthhiiss aapppprrooaacchh iinn 
CCooddee FFrraaggmmeenntt 55..1166,, wwhhiicchh ddeessccrriibbeess aa ssoolluuttiioonn tthhaatt 
rruunnss iinn OO((nnkk)) ttiimmee.. ((WWee ccaann ssoollvvee tthhiiss pprroobblleemm ffaasstteerr 
uussiinngg tteecchhnniiqquueess bbeeyyoonndd tthhee ssccooppee ooff tthhiiss bbooookk..))
Code Fragment 5.16: A complete Java program for solving the Josephus problem 
using a queue. Class NodeQueue is shown in Code Fragment 5.15.

More Related Content

What's hot

Catch-me if you can - TOR tricks for bots, shells and general hacking
Catch-me if you can - TOR tricks for bots, shells and general hackingCatch-me if you can - TOR tricks for bots, shells and general hacking
Catch-me if you can - TOR tricks for bots, shells and general hacking
Jan Seidl
 
Epoch, definitions of terrorism
Epoch, definitions of terrorismEpoch, definitions of terrorism
Epoch, definitions of terrorism
Janos Tomolya
 
Motivação de pessoas ganhadora.
Motivação de pessoas ganhadora.Motivação de pessoas ganhadora.
Motivação de pessoas ganhadora.
Pr Ezeq Rodrigues
 
Radio communication resum
  Radio   communication resum  Radio   communication resum
Radio communication resum
Rabah HELAL
 
Introduction to parts of speech tagging
Introduction to parts of speech taggingIntroduction to parts of speech tagging
Introduction to parts of speech tagging
azra01
 
POWER POINT PRESENTATION
POWER POINT PRESENTATIONPOWER POINT PRESENTATION
POWER POINT PRESENTATION
SARANYALAL
 
Apoptosis
ApoptosisApoptosis
Marshall mix design method
Marshall mix design methodMarshall mix design method
Marshall mix design method
Gourav Mewara
 
Palestra feso antibióticos 2014
Palestra feso antibióticos 2014Palestra feso antibióticos 2014
Palestra feso antibióticos 2014
Leonora Mello
 
GastritisZaydoon
GastritisZaydoonGastritisZaydoon
GastritisZaydoonZay Doon
 
Tipos de planos y ángulos de cámara
Tipos de planos y ángulos de cámaraTipos de planos y ángulos de cámara
Tipos de planos y ángulos de cámara
Nabil Rodriguez Barraza
 
Mixed degenerations
Mixed degenerationsMixed degenerations
Mixed degenerations
nizhgma.ru
 
Farmasetika (Sediaan luar)
Farmasetika (Sediaan luar)Farmasetika (Sediaan luar)
Farmasetika (Sediaan luar)
Stikes BTH Tasikmalaya
 
смешанные дистрофии англ.
смешанные дистрофии англ.смешанные дистрофии англ.
смешанные дистрофии англ.
nizhgma.ru
 
фоис мезенх дистр
фоис мезенх дистрфоис мезенх дистр
фоис мезенх дистр
nizhgma.ru
 

What's hot (19)

Catch-me if you can - TOR tricks for bots, shells and general hacking
Catch-me if you can - TOR tricks for bots, shells and general hackingCatch-me if you can - TOR tricks for bots, shells and general hacking
Catch-me if you can - TOR tricks for bots, shells and general hacking
 
Epoch, definitions of terrorism
Epoch, definitions of terrorismEpoch, definitions of terrorism
Epoch, definitions of terrorism
 
Motivação de pessoas ganhadora.
Motivação de pessoas ganhadora.Motivação de pessoas ganhadora.
Motivação de pessoas ganhadora.
 
Radio communication resum
  Radio   communication resum  Radio   communication resum
Radio communication resum
 
Ra lecture - muscles of the face
Ra   lecture - muscles of the faceRa   lecture - muscles of the face
Ra lecture - muscles of the face
 
Introduction to parts of speech tagging
Introduction to parts of speech taggingIntroduction to parts of speech tagging
Introduction to parts of speech tagging
 
PANKAJ
PANKAJPANKAJ
PANKAJ
 
Proj mangmt 22
Proj mangmt 22Proj mangmt 22
Proj mangmt 22
 
POWER POINT PRESENTATION
POWER POINT PRESENTATIONPOWER POINT PRESENTATION
POWER POINT PRESENTATION
 
Apoptosis
ApoptosisApoptosis
Apoptosis
 
Marshall mix design method
Marshall mix design methodMarshall mix design method
Marshall mix design method
 
Palestra feso antibióticos 2014
Palestra feso antibióticos 2014Palestra feso antibióticos 2014
Palestra feso antibióticos 2014
 
GastritisZaydoon
GastritisZaydoonGastritisZaydoon
GastritisZaydoon
 
Tipos de planos y ángulos de cámara
Tipos de planos y ángulos de cámaraTipos de planos y ángulos de cámara
Tipos de planos y ángulos de cámara
 
Mixed degenerations
Mixed degenerationsMixed degenerations
Mixed degenerations
 
Lecture 05
Lecture 05Lecture 05
Lecture 05
 
Farmasetika (Sediaan luar)
Farmasetika (Sediaan luar)Farmasetika (Sediaan luar)
Farmasetika (Sediaan luar)
 
смешанные дистрофии англ.
смешанные дистрофии англ.смешанные дистрофии англ.
смешанные дистрофии англ.
 
фоис мезенх дистр
фоис мезенх дистрфоис мезенх дистр
фоис мезенх дистр
 

Viewers also liked

Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis tools
Abdullah Al-hazmy
 
Data Structures- Part9 trees simplified
Data Structures- Part9 trees simplifiedData Structures- Part9 trees simplified
Data Structures- Part9 trees simplified
Abdullah Al-hazmy
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
Data Structures- Part4 basic sorting algorithms
Data Structures- Part4 basic sorting algorithmsData Structures- Part4 basic sorting algorithms
Data Structures- Part4 basic sorting algorithms
Abdullah Al-hazmy
 
9781111530532 ppt ch14
9781111530532 ppt ch149781111530532 ppt ch14
9781111530532 ppt ch14Terry Yoast
 
9781285852744 ppt ch16
9781285852744 ppt ch169781285852744 ppt ch16
9781285852744 ppt ch16
Terry Yoast
 
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
Amazon Web Services Korea
 
Applying Design Patterns in Practice
Applying Design Patterns in PracticeApplying Design Patterns in Practice
Applying Design Patterns in Practice
Ganesh Samarthyam
 
AWS ECS Quick Introduction
AWS ECS Quick IntroductionAWS ECS Quick Introduction
AWS ECS Quick Introduction
Vinothini Raju
 
Web Database
Web DatabaseWeb Database
Web Database
idroos7
 
Data Structures- Part7 linked lists
Data Structures- Part7 linked listsData Structures- Part7 linked lists
Data Structures- Part7 linked lists
Abdullah Al-hazmy
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8
Garth Gilmour
 
Java 8 Support at the JVM Level
Java 8 Support at the JVM LevelJava 8 Support at the JVM Level
Java 8 Support at the JVM Level
Nikita Lipsky
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
Fahad Shaikh
 
Building Digital Transaction Systems in the new Banking World
Building Digital Transaction Systems in the new Banking WorldBuilding Digital Transaction Systems in the new Banking World
Building Digital Transaction Systems in the new Banking World
Ramit Surana
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for javamaheshm1206
 
Arrays Basics
Arrays BasicsArrays Basics
Arrays Basics
Nikhil Pandit
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
Iram Ramrajkar
 

Viewers also liked (20)

Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis tools
 
Data Structures- Part9 trees simplified
Data Structures- Part9 trees simplifiedData Structures- Part9 trees simplified
Data Structures- Part9 trees simplified
 
Lecture 2a arrays
Lecture 2a arraysLecture 2a arrays
Lecture 2a arrays
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Data Structures- Part4 basic sorting algorithms
Data Structures- Part4 basic sorting algorithmsData Structures- Part4 basic sorting algorithms
Data Structures- Part4 basic sorting algorithms
 
9781111530532 ppt ch14
9781111530532 ppt ch149781111530532 ppt ch14
9781111530532 ppt ch14
 
Chap01
Chap01Chap01
Chap01
 
9781285852744 ppt ch16
9781285852744 ppt ch169781285852744 ppt ch16
9781285852744 ppt ch16
 
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
 
Applying Design Patterns in Practice
Applying Design Patterns in PracticeApplying Design Patterns in Practice
Applying Design Patterns in Practice
 
AWS ECS Quick Introduction
AWS ECS Quick IntroductionAWS ECS Quick Introduction
AWS ECS Quick Introduction
 
Web Database
Web DatabaseWeb Database
Web Database
 
Data Structures- Part7 linked lists
Data Structures- Part7 linked listsData Structures- Part7 linked lists
Data Structures- Part7 linked lists
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8
 
Java 8 Support at the JVM Level
Java 8 Support at the JVM LevelJava 8 Support at the JVM Level
Java 8 Support at the JVM Level
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
Building Digital Transaction Systems in the new Banking World
Building Digital Transaction Systems in the new Banking WorldBuilding Digital Transaction Systems in the new Banking World
Building Digital Transaction Systems in the new Banking World
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Arrays Basics
Arrays BasicsArrays Basics
Arrays Basics
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 

Similar to Data Structures- Part8 stacks and queues

The digestive-system-powerpoint-
The digestive-system-powerpoint-The digestive-system-powerpoint-
The digestive-system-powerpoint-abreham abush
 
Literary appreciation
Literary appreciationLiterary appreciation
Literary appreciation
Reny Eka Sari
 
Economics of terrorism ihs webinar
Economics of terrorism   ihs webinarEconomics of terrorism   ihs webinar
Economics of terrorism ihs webinar
LearnLiberty
 
Lesson 6 day 1
Lesson 6 day 1Lesson 6 day 1
Speaker ppt
Speaker pptSpeaker ppt
Speaker ppt
Anubhav Sokhal
 
Creating the Startup The Accounting Panorama
Creating the Startup The Accounting PanoramaCreating the Startup The Accounting Panorama
Creating the Startup The Accounting Panorama
Steve Lines
 
4th grade, lesson plan
4th grade, lesson plan4th grade, lesson plan
4th grade, lesson plan
cpapadak
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and sets
maznabili
 
Lesson 6 day 2
Lesson 6 day 2Lesson 6 day 2
Geologic time
Geologic timeGeologic time
Geologic time
Crossleybp
 
Ribbon of life
Ribbon of lifeRibbon of life
Ribbon of life
Celeste Bafundo
 
HTML basic
HTML basicHTML basic
HTML basic
Yoeung Vibol
 
Medical legal in Neurosurgery
Medical legal in NeurosurgeryMedical legal in Neurosurgery
Medical legal in Neurosurgery
Liew Boon Seng
 
Training methods
Training methodsTraining methods
Training methods
begraj SIWAL
 
Sistema Respiratorio 1
Sistema Respiratorio 1Sistema Respiratorio 1
Sistema Respiratorio 1
eduardo felipe peña morales
 
Workshop II digital literacy presentation
Workshop II digital literacy presentationWorkshop II digital literacy presentation
Workshop II digital literacy presentation
Elizabeth Allen
 
Ppt fuzzy 3 final presentation (1)
Ppt fuzzy 3 final presentation (1)Ppt fuzzy 3 final presentation (1)
Ppt fuzzy 3 final presentation (1)13pps007
 
Clinical anatomy of the upper limb
Clinical anatomy of the upper limb Clinical anatomy of the upper limb
Clinical anatomy of the upper limb
Muhammad Ramzan Ul Rehman
 
[Slideshare] fiqh-course (august 2014-batch) -# 11-advice-regading-contempora...
[Slideshare] fiqh-course (august 2014-batch) -# 11-advice-regading-contempora...[Slideshare] fiqh-course (august 2014-batch) -# 11-advice-regading-contempora...
[Slideshare] fiqh-course (august 2014-batch) -# 11-advice-regading-contempora...Zhulkeflee Ismail
 

Similar to Data Structures- Part8 stacks and queues (20)

The digestive-system-powerpoint-
The digestive-system-powerpoint-The digestive-system-powerpoint-
The digestive-system-powerpoint-
 
Literary appreciation
Literary appreciationLiterary appreciation
Literary appreciation
 
Economics of terrorism ihs webinar
Economics of terrorism   ihs webinarEconomics of terrorism   ihs webinar
Economics of terrorism ihs webinar
 
Lesson 6 day 1
Lesson 6 day 1Lesson 6 day 1
Lesson 6 day 1
 
Speaker ppt
Speaker pptSpeaker ppt
Speaker ppt
 
Creating the Startup The Accounting Panorama
Creating the Startup The Accounting PanoramaCreating the Startup The Accounting Panorama
Creating the Startup The Accounting Panorama
 
4th grade, lesson plan
4th grade, lesson plan4th grade, lesson plan
4th grade, lesson plan
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and sets
 
Lesson 6 day 2
Lesson 6 day 2Lesson 6 day 2
Lesson 6 day 2
 
Geologic time
Geologic timeGeologic time
Geologic time
 
Ribbon of life
Ribbon of lifeRibbon of life
Ribbon of life
 
HTML basic
HTML basicHTML basic
HTML basic
 
Medical legal in Neurosurgery
Medical legal in NeurosurgeryMedical legal in Neurosurgery
Medical legal in Neurosurgery
 
Training methods
Training methodsTraining methods
Training methods
 
Sistema Respiratorio 1
Sistema Respiratorio 1Sistema Respiratorio 1
Sistema Respiratorio 1
 
Workshop II digital literacy presentation
Workshop II digital literacy presentationWorkshop II digital literacy presentation
Workshop II digital literacy presentation
 
Ppt fuzzy 3 final presentation (1)
Ppt fuzzy 3 final presentation (1)Ppt fuzzy 3 final presentation (1)
Ppt fuzzy 3 final presentation (1)
 
Clinical anatomy of the upper limb
Clinical anatomy of the upper limb Clinical anatomy of the upper limb
Clinical anatomy of the upper limb
 
[Slideshare] fiqh-course (august 2014-batch) -# 11-advice-regading-contempora...
[Slideshare] fiqh-course (august 2014-batch) -# 11-advice-regading-contempora...[Slideshare] fiqh-course (august 2014-batch) -# 11-advice-regading-contempora...
[Slideshare] fiqh-course (august 2014-batch) -# 11-advice-regading-contempora...
 
Synectics
SynecticsSynectics
Synectics
 

Data Structures- Part8 stacks and queues

  • 2. WWhhaatt iiss aa SSttaacckk??  SSttaacckk iiss aa ddaattaa ssttrruuccttuurree iinn wwhhiicchh ddaattaa iiss aaddddeedd aanndd rreemmoovveedd aatt oonnllyy oonnee eenndd ccaalllleedd tthhee ttoopp  EExxaammpplleess ooff ssttaacckkss aarree::  SSttaacckk ooff bbooookkss  SSttaacckk ooff ttrraayyss iinn aa ccaaffeetteerriiaa
  • 3. SSttaacckk  AA LLaasstt IInn FFiirrsstt OOuutt ((LLIIFFOO)) ddaattaa ssttrruuccttuurree  PPrriimmaarryy ooppeerraattiioonnss:: PPuusshh aanndd PPoopp  PPuusshh  AAdddd aann eelleemmeenntt ttoo tthhee ttoopp ooff tthhee ssttaacckk  PPoopp  RReemmoovvee tthhee eelleemmeenntt ffrroomm tthhee ttoopp ooff tthhee ssttaacckk  AAnn eexxaammppllee empty stack: initial state top top A top top push (A) push (B) B A pop A
  • 4. BBuuiillddiinngg SSttaacckk SStteepp--bbyy--SStteepp 2 8 1 7 2 1 7 2 7 2 1 7 2 8 1 7 2 8 1 7 2 top top top top top top Push(8) Push(2) pop() pop() pop()
  • 5. SSttaacckk EErrrroorrss  SSttaacckk OOvveerrffllooww  AAnn aatttteemmpptt ttoo aadddd aa nneeww eelleemmeenntt iinn aann aallrreeaaddyy ffuullll ssttaacckk iiss aann eerrrroorr  AA ccoommmmoonn mmiissttaakkee oofftteenn mmaaddee iinn ssttaacckk iimmpplleemmeennttaattiioonn  SSttaacckk UUnnddeerrffllooww  AAnn aatttteemmpptt ttoo rreemmoovvee aann eelleemmeenntt ffrroomm tthhee eemmppttyy ssttaacckk iiss aallssoo aann eerrrroorr  AAggaaiinn,, aa ccoommmmoonn mmiissttaakkee oofftteenn mmaaddee iinn ssttaacckk iimmpplleemmeennttaattiioonn
  • 6. AApppplliiccaattiioonnss ooff SSttaacckkss  SSoommee ddiirreecctt aapppplliiccaattiioonnss::  PPaaggee--vviissiitteedd hhiissttoorryy iinn aa WWeebb bbrroowwsseerr  UUnnddoo sseeqquueennccee iinn aa tteexxtt eeddiittoorr  EEvvaalluuaattiinngg ppoossttffiixx eexxpprreessssiioonnss ((ee..gg..,, xxyy++))  SSoommee iinnddiirreecctt aapppplliiccaattiioonnss  AAuuxxiilliiaarryy ddaattaa ssttrruuccttuurree ffoorr ssoommee aallggoorriitthhmmss ((ee..gg..,, DDeepptthh FFiirrsstt SSeeaarrcchh aallggoorriitthhmm))  CCoommppoonneenntt ooff ootthheerr ddaattaa ssttrruuccttuurreess
  • 7. TThhee SSttaacckk AAbbssttrraacctt DDaattaa TTyyppee  SSttaacckkss aarree tthhee ssiimmpplleesstt ooff aallll ddaattaa ssttrruuccttuurreess  FFoorrmmaallllyy,, aa ssttaacckk iiss aann aabbssttrraacctt ddaattaa ttyyppee ((AADDTT)) tthhaatt ssuuppppoorrttss tthhee ffoolllloowwiinngg ttwwoo mmeetthhooddss::  ppuusshh((ee)):: IInnsseerrtt eelleemmeenntt ee ttoo tthhee ttoopp ooff tthhee ssttaacckk  ppoopp(()):: RReemmoovvee ffrroomm tthhee ssttaacckk aanndd rreettuurrnn tthhee ttoopp eelleemmeenntt oonn tthhee ssttaacckk;;  aann eerrrroorr ooccccuurrss iiff tthhee ssttaacckk iiss eemmppttyy –– wwhhaatt eerrrroorr??  AAddddiittiioonnaallllyy,, lleett uuss aallssoo ddeeffiinnee tthhee ffoolllloowwiinngg mmeetthhooddss::  ssiizzee(()):: RReettuurrnn tthhee nnuummbbeerr ooff eelleemmeennttss iinn tthhee ssttaacckk  iissEEmmppttyy(()):: RReettuurrnn aa BBoooolleeaann iinnddiiccaattiinngg iiff tthhee ssttaacckk iiss eemmppttyy  ttoopp(()):: RReettuurrnn tthhee ttoopp eelleemmeenntt iinn tthhee ssttaacckk,, wwiitthhoouutt rreemmoovviinngg iitt aann eerrrroorr ooccccuurrss iiff tthhee ssttaacckk iiss eemmppttyy
  • 8. TThhee SSttaacckk AAbbssttrraacctt DDaattaa TTyyppee  EExxaammppllee 55..33:: TThhee ffoolllloowwiinngg ttaabbllee sshhoowwss aa sseerriieess ooff ssttaacckk ooppeerraattiioonnss aanndd tthheeiirr eeffffeeccttss oonn aann iinniittiiaallllyy eemmppttyy ssttaacckk SS ooff iinntteeggeerrss.. OOppeerraattiioonn OOuuttppuutt SSttaacckk CCoonntteennttss ppuusshh((55)) ppuusshh((33)) ppoopp(()) ppuusshh((77)) ppoopp(()) ttoopp(()) ppoopp(()) ppoopp(()) iissEEmmppttyy(()) ppuusshh((99)) ppuusshh((77)) ppuusshh((33)) ppuusshh((55)) ssiizzee(()) ppoopp(()) ppuusshh((88)) ppoopp(()) ppoopp(()) -- -- 33- - 77 55 55 ""eerrrroorr““ ttrruuee -- -- -- -- 44 55- - 88 33 ((55)) ((55,, 33)) ((55)) ((55,, 77)) ((55)) ((55)) (()) (()) (()) ((99)) ((99,, 77)) ((99,, 77,, 33)) ((99,, 77,, 33,, 55)) ((99,, 77,, 33,, 55)) ((99,, 77,, 33)) ((99,, 77,, 33,, 88)) ((99,, 77,, 33)) ((99,, 77))
  • 9. AA SSttaacckk IInntteerrffaaccee iinn JJaavvaa  TThhee ssttaacckk ddaattaa ssttrruuccttuurree iiss iinncclluuddeedd aass aa ""bbuuiilltt-- iinn"" ccllaassss iinn tthhee jjaavvaa..uuttiill ppaacckkaaggee ooff JJaavvaa..  CCllaassss jjaavvaa..uuttiill..SSttaacckk iiss aa ddaattaa ssttrruuccttuurree tthhaatt ssttoorreess ggeenneerriicc JJaavvaa oobbjjeeccttss aanndd iinncclluuddeess,,aammoonngg ootthheerrss,, tthhee ffoolllloowwiinngg mmeetthhooddss::  ppuusshh(()),,  ppoopp(())  ppeeeekk(()) ((eeqquuiivvaalleenntt ttoo ttoopp(()))),,  ssiizzee(()),, aanndd eemmppttyy(()) ((eeqquuiivvaalleenntt ttoo iissEEmmppttyy(()))).. MMeetthhooddss ppoopp(()) aanndd ppeeeekk(()) tthhrrooww eexxcceeppttiioonn EEmmppttyySSttaacckkEExxcceeppttiioonn iiff tthheeyy aarree ccaalllleedd oonn aann eemmppttyy ssttaacckk..
  • 10. TThhee SSttaacckk AAbbssttrraacctt DDaattaa TTyyppee  IImmpplleemmeennttiinngg aann aabbssttrraacctt ddaattaa ttyyppee iinn JJaavvaa iinnvvoollvveess ttwwoo sstteeppss.. TThhee ffiirrsstt sstteepp iiss tthhee ddeeffiinniittiioonn ooff aa JJaavvaa AApppplliiccaattiioonn PPrrooggrraammmmiinngg IInntteerrffaaccee ((AAPPII)),, oorr ssiimmppllyy iinntteerrffaaccee,, wwhhiicchh ddeessccrriibbeess tthhee nnaammeess ooff tthhee mmeetthhooddss tthhaatt tthhee AADDTT ssuuppppoorrttss aanndd hhooww tthheeyy aarree ttoo bbee ddeeccllaarreedd aanndd uusseedd..  IInn aaddddiittiioonn,, wwee mmuusstt ddeeffiinnee eexxcceeppttiioonnss ffoorr aannyy eerrrroorr ccoonnddiittiioonnss tthhaatt ccaann aarriissee.. FFoorr iinnssttaannccee,, tthhee eerrrroorr ccoonnddiittiioonn tthhaatt ooccccuurrss wwhheenn ccaalllliinngg mmeetthhoodd ppoopp(()) oorr ttoopp(()) oonn aann eemmppttyy ssttaacckk iiss ssiiggnnaalleedd bbyy tthhrroowwiinngg aann eexxcceeppttiioonn ooff ttyyppee EEmmppttyySSttaacckkEExxcceeppttiioonn,,
  • 11. TThhee SSttaacckk AAbbssttrraacctt DDaattaa TTyyppee CCooddee FFrraaggmmeenntt 55..22:: IInntteerrffaaccee SSttaacckk ddooccuummeenntteedd wwiitthh ccoommmmeennttss iinn JJaavvaaddoocc ssttyyllee ((SSeeccttiioonn 11..99..33)).. NNoottee aallssoo tthhee uussee ooff tthhee ggeenneerriicc ppaarraammeetteerriizzeedd ttyyppee,, EE,, wwhhiicchh iimmpplliieess tthhaatt aa ssttaacckk ccaann ccoonnttaaiinn eelleemmeennttss ooff aannyy ssppeecciiffiieedd ccllaassss..
  • 12. AA SSiimmppllee AArrrraayy--BBaasseedd SSttaacckk IImmpplleemmeennttaattiioonn  WWee ccaann iimmpplleemmeenntt aa ssttaacckk bbyy ssttoorriinngg iittss eelleemmeennttss iinn aann aarrrraayy..  SSppeecciiffiiccaallllyy,, tthhee ssttaacckk iinn tthhiiss iimmpplleemmeennttaattiioonn ccoonnssiissttss ooff  aann NN--eelleemmeenntt aarrrraayy SS  pplluuss aann iinntteeggeerr vvaarriiaabbllee tt tthhaatt ggiivveess tthhee iinnddeexx ooff tthhee ttoopp eelleemmeenntt iinn aarrrraayy SS.. FFiigguurree 55..22:: IImmpplleemmeennttiinngg aa ssttaacckk wwiitthh aann aarrrraayy SS.. TThhee ttoopp eelleemmeenntt iinn tthhee ssttaacckk iiss ssttoorreedd iinn tthhee cceellll SS[[tt]]..  RReeccaalllliinngg tthhaatt aarrrraayyss ssttaarrtt aatt iinnddeexx 00 iinn JJaavvaa,,  wwee iinniittiiaalliizzee tt ttoo −−11,, aanndd wwee uussee tthhiiss vvaalluuee ffoorr tt ttoo iiddeennttiiffyy aann eemmppttyy ssttaacckk..  LLiikkeewwiissee,, wwee ccaann uussee tt ttoo ddeetteerrmmiinnee tthhee nnuummbbeerr ooff eelleemmeennttss ((tt ++ 11))..  FFuullllSSttaacckkEExxcceeppttiioonn,, ttoo ssiiggnnaall tthhee eerrrroorr tthhaatt aarriisseess iiff wwee ttrryy ttoo iinnsseerrtt aa nneeww eelleemmeenntt iinnttoo aa ffuullll aarrrraayy..  EExxcceeppttiioonn FFuullllSSttaacckkEExxcceeppttiioonn iiss ssppeecciiffiicc ttoo tthhiiss iimmpplleemmeennttaattiioonn aanndd iiss nnoott ddeeffiinneedd iinn tthhee ssttaacckk AADDTT..
  • 13. CCooddee FFrraaggmmeenntt 55..33:: IImmpplleemmeennttiinngg aa ssttaacckk uussiinngg aann aarrrraayy ooff aa ggiivveenn ssiizzee,, NN..
  • 14. Analyzing tthhee AArrrraayy--BBaasseedd SSttaacckk IImmpplleemmeennttaattiioonn  TThhee ccoorrrreeccttnneessss ooff tthhee mmeetthhooddss iinn tthhee aarrrraayy--bbaasseedd iimmpplleemmeennttaattiioonn ffoolllloowwss iimmmmeeddiiaatteellyy ffrroomm tthhee ddeeffiinniittiioonn ooff tthhee mmeetthhooddss tthheemmsseellvveess..  NNoottee tthhaatt wwee ccoouulldd hhaavvee aavvooiiddeedd rreesseettttiinngg tthhee oolldd SS[[tt]] ttoo nnuullll aanndd wwee wwoouulldd ssttiillll hhaavvee aa ccoorrrreecctt mmeetthhoodd..  TThheerree iiss aa ttrraaddee--ooffff iinn bbeeiinngg aabbllee ttoo aavvooiidd tthhiiss aassssiiggnnmmeenntt sshhoouulldd wwee bbee tthhiinnkkiinngg aabboouutt iimmpplleemmeennttiinngg tthheessee aallggoorriitthhmmss iinn JJaavvaa..  TThhee ttrraaddee--ooffff iinnvvoollvveess tthhee JJaavvaa ggaarrbbaaggee ccoolllleeccttiioonn mmeecchhaanniissmm tthhaatt sseeaarrcchheess mmeemmoorryy ffoorr oobbjjeeccttss tthhaatt aarree nnoo lloonnggeerr rreeffeerreenncceedd bbyy aaccttiivvee oobbjjeeccttss,, aanndd rreeccllaaiimmss tthheeiirr ssppaaccee ffoorr ffuuttuurree uussee.. LLeett ee == SS[[tt]] bbee tthhee ttoopp eelleemmeenntt bbeeffoorree tthhee ppoopp mmeetthhoodd iiss ccaalllleedd..  BByy mmaakkiinngg SS[[tt]] aa nnuullll rreeffeerreennccee,, wwee iinnddiiccaattee tthhaatt tthhee ssttaacckk nnoo lloonnggeerr nneeeeddss ttoo hhoolldd aa rreeffeerreennccee ttoo oobbjjeecctt ee.. IInnddeeeedd,, iiff tthheerree aarree nnoo ootthheerr aaccttiivvee rreeffeerreenncceess ttoo ee,, tthheenn tthhee mmeemmoorryy ssppaaccee ttaakkeenn bbyy ee wwiillll bbee rreeccllaaiimmeedd bbyy tthhee ggaarrbbaaggee ccoolllleeccttoorr..  TTaabbllee 55..11 sshhoowwss tthhee rruunnnniinngg ttiimmeess ffoorr mmeetthhooddss iinn aa rreeaalliizzaattiioonn ooff aa ssttaacckk bbyy aann aarrrraayy.. EEaacchh ooff tthhee ssttaacckk mmeetthhooddss iinn tthhee aarrrraayy rreeaalliizzaattiioonn eexxeeccuutteess aa ccoonnssttaanntt nnuummbbeerr ooff ssttaatteemmeennttss iinnvvoollvviinngg aarriitthhmmeettiicc ooppeerraattiioonnss,, ccoommppaarriissoonnss,, aanndd aassssiiggnnmmeennttss..  IInn aaddddiittiioonn,, ppoopp aallssoo ccaallllss iissEEmmppttyy,, wwhhiicchh iittsseellff rruunnss iinn ccoonnssttaanntt ttiimmee.. TThhuuss,, iinn tthhiiss iimmpplleemmeennttaattiioonn ooff tthhee SSttaacckk AADDTT,, eeaacchh mmeetthhoodd rruunnss iinn ccoonnssttaanntt ttiimmee,, tthhaatt iiss,, tthheeyy eeaacchh rruunn iinn OO((11)) ttiimmee..
  • 15.  TTaabbllee 55..11:: PPeerrffoorrmmaannccee ooff aa ssttaacckk rreeaalliizzeedd bbyy aann aarrrraayy.. TThhee ssppaaccee uussaaggee iiss OO((NN)),, wwhheerree NN iiss tthhee ssiizzee ooff tthhee aarrrraayy,, ddeetteerrmmiinneedd aatt tthhee ttiimmee tthhee ssttaacckk iiss iinnssttaannttiiaatteedd.. NNoottee tthhaatt tthhee ssppaaccee uussaaggee iiss iinnddeeppeennddeenntt ffrroomm tthhee nnuummbbeerr nn ≤≤ NN ooff eelleemmeennttss tthhaatt aarree aaccttuuaallllyy iinn tthhee ssttaacckk.. MMeetthhoodd TTiimmee ssiizzee OO((11)) iiss EEmmppttyy OO((11)) ttoopp OO((11)) ppuusshh OO((11)) ppoopp OO((11))
  • 16. A Drawback wwiitthh tthhee AArrrraayy--BBaasseedd SSttaacckk IImmpplleemmeennttaattiioonn  The array implementation of a stack is simple and efficient.  This implementation has one negative aspect  it must assume a fixed upper bound, CAPACITY, on the ultimate size of the stack.  In Code Fragment 5.4, we chose the capacity value 1,000 more or less arbitrarily.  An application may actually need much less space than this,  which would waste memory.  An application may need more space than this,  which would cause our stack implementation to generate an exception as soon as a client program tries to push its 1,001st object on the stack.  Thus, even with its simplicity and efficiency, the array-based stack implementation is not necessarily ideal.  Fortunately, there is another implementation, which we discuss next,  that does not have a size limitation  and use space proportional to the actual number of elements stored in the stack.  Still, in cases where we have a good estimate on the number of items needing to go in the stack,  the array-based implementation is hard to beat.  Stacks serve a vital role in a number of computing applications, so it is helpful to have a fast stack ADT implementation such as the simple array-based implementation.
  • 17. Implementing aa SSttaacckk wwiitthh aa GGeenneerriicc LLiinnkkeedd LLiisstt  UUssiinngg aa ssiinnggllyy lliinnkkeedd lliisstt ttoo iimmpplleemmeenntt tthhee ssttaacckk AADDTT..  IInn ddeessiiggnniinngg ssuucchh aann iimmpplleemmeennttaattiioonn,, wwee nneeeedd ttoo ddeecciiddee iiff  tthhee ttoopp ooff tthhee ssttaacckk iiss aatt tthhee hheeaadd  oorr aatt tthhee ttaaiill ooff tthhee lliisstt..  SSiinnccee wwee ccaann iinnsseerrtt aanndd ddeelleettee eelleemmeennttss iinn ccoonnssttaanntt ttiimmee oonnllyy aatt tthhee hheeaadd..  TThhuuss,, iitt iiss mmoorree eeffffiicciieenntt ttoo hhaavvee tthhee ttoopp ooff tthhee ssttaacckk aatt tthhee hheeaadd ooff oouurr lliisstt..  iinn oorrddeerr ttoo ppeerrffoorrmm ooppeerraattiioonn ssiizzee iinn ccoonnssttaanntt ttiimmee,,  wwee kkeeeepp ttrraacckk ooff tthhee ccuurrrreenntt nnuummbbeerr ooff eelleemmeennttss iinn aann iinnssttaannccee vvaarriiaabbllee..  RRaatthheerr tthhaann uussee aa lliinnkkeedd lliisstt tthhaatt ccaann oonnllyy ssttoorree oobbjjeeccttss ooff aa cceerrttaaiinn ttyyppee,, wwee wwoouulldd lliikkee,, iinn tthhiiss ccaassee,, ttoo iimmpplleemmeenntt aa ggeenneerriicc ssttaacckk uussiinngg aa ggeenneerriicc lliinnkkeedd lliisstt..  TThhuuss,, wwee nneeeedd ttoo uussee aa ggeenneerriicc kkiinndd ooff nnooddee ttoo iimmpplleemmeenntt tthhiiss lliinnkkeedd lliisstt.. WWee sshhooww ssuucchh aa NNooddee ccllaassss iinn CCooddee FFrraaggmmeenntt 55..6..
  • 18. Implementing aa SSttaacckk wwiitthh aa GGeenneerriicc LLiinnkkeedd LLiisstt  CCooddee FFrraaggmmeenntt 55..6:: CCllaassss NNooddee,, wwhhiicchh iimmpplleemmeennttss aa ggeenneerriicc nnooddee ffoorr aa ssiinnggllyy lliinnkkeedd lliisstt.. 
  • 19. AA GGeenneerriicc NNooddeeSSttaacckk CCllaassss  AA JJaavvaa iimmpplleemmeennttaattiioonn ooff aa ssttaacckk,, bbyy mmeeaannss ooff aa ggeenneerriicc ssiinnggllyy lliinnkkeedd lliisstt,, iiss ggiivveenn iinn CCooddee FFrraaggmmeenntt 55..77..  AAllll tthhee mmeetthhooddss ooff tthhee SSttaacckk iinntteerrffaaccee aarree eexxeeccuutteedd iinn ccoonnssttaanntt ttiimmee..  IInn aaddddiittiioonn ttoo bbeeiinngg ttiimmee eeffffiicciieenntt,, tthhiiss lliinnkkeedd lliisstt iimmpplleemmeennttaattiioonn hhaass aa ssppaaccee rreeqquuiirreemmeenntt tthhaatt iiss OO((nn)),, wwhheerree nn iiss tthhee ccuurrrreenntt nnuummbbeerr ooff eelleemmeennttss iinn tthhee ssttaacckk..  TThhuuss,, tthhiiss iimmpplleemmeennttaattiioonn ddooeess nnoott rreeqquuiirree tthhaatt aa nneeww eexxcceeppttiioonn bbee ccrreeaatteedd ttoo hhaannddllee ssiizzee oovveerrffllooww pprroobblleemmss.. WWee uussee aann iinnssttaannccee vvaarriiaabbllee ttoopp ttoo rreeffeerr ttoo tthhee hheeaadd ooff tthhee lliisstt ((wwhhiicchh ppooiinnttss ttoo tthhee nnuullll oobbjjeecctt iiff tthhee lliisstt iiss eemmppttyy))..  WWhheenn wwee ppuusshh aa nneeww eelleemmeenntt ee oonn tthhee ssttaacckk,, wwee ssiimmppllyy ccrreeaattee aa nneeww nnooddee vv ffoorr ee,, rreeffeerreennccee ee ffrroomm vv,, aanndd iinnsseerrtt vv aatt tthhee hheeaadd ooff tthhee lliisstt..  LLiikkeewwiissee,, wwhheenn wwee ppoopp aann eelleemmeenntt ffrroomm tthhee ssttaacckk,, wwee ssiimmppllyy rreemmoovvee tthhee nnooddee aatt tthhee hheeaadd ooff tthhee lliisstt aanndd rreettuurrnn iittss eelleemmeenntt.. TThhuuss,, wwee ppeerrffoorrmm aallll iinnsseerrttiioonnss aanndd rreemmoovvaallss ooff eelleemmeennttss aatt tthhee hheeaadd ooff tthhee lliisstt..
  • 20. Code Fragment 5.7: Class NodeStack, which implements the Stack interface using a singly linked list, whose nodes are objects of class Node from Code Fragment 5.6.
  • 21. Reversing aann AArrrraayy UUssiinngg aa SSttaacckk  WWee ccaann uussee aa ssttaacckk ttoo rreevveerrssee tthhee eelleemmeennttss iinn aann aarrrraayy,,  tthheerreebbyy pprroodduucciinngg aa nnoonnrreeccuurrssiivvee aallggoorriitthhmm ffoorr tthhee aarrrraayy--rreevveerrssaall pprroobblleemm iinnttrroodduucceedd iinn SSeeccttiioonn 33..55..11..  TThhee bbaassiicc iiddeeaa iiss ssiimmppllyy ttoo ppuusshh aallll tthhee eelleemmeennttss ooff tthhee aarrrraayy iinn oorrddeerr iinnttoo aa ssttaacckk aanndd tthheenn ffiillll tthhee aarrrraayy bbaacckk uupp aaggaaiinn bbyy ppooppppiinngg tthhee eelleemmeennttss ooffff ooff tthhee ssttaacckk..  IInn CCooddee FFrraaggmmeenntt 55..88,, wwee ggiivvee aa JJaavvaa iimmpplleemmeennttaattiioonn ooff tthhiiss aallggoorriitthhmm.. IInncciiddeennttaallllyy,, tthhiiss mmeetthhoodd aallssoo iilllluussttrraatteess hhooww wwee ccaann uussee ggeenneerriicc ttyyppeess iinn aa ssiimmppllee aapppplliiccaattiioonn tthhaatt uusseess aa ggeenneerriicc ssttaacckk..  IInn ppaarrttiiccuullaarr,, wwhheenn tthhee eelleemmeennttss aarree ppooppppeedd ooffff tthhee ssttaacckk iinn tthhiiss eexxaammppllee,, tthheeyy aarree aauuttoommaattiiccaallllyy rreettuurrnneedd aass eelleemmeennttss ooff tthhee EE ttyyppee;; hheennccee,, tthheeyy ccaann bbee iimmmmeeddiiaatteellyy rreettuurrnneedd ttoo tthhee iinnppuutt aarrrraayy.. WWee sshhooww aann eexxaammppllee uussee ooff tthhiiss mmeetthhoodd iinn CCooddee FFrraaggmmeenntt 55..99..
  • 22. Code Fragment 5.8: A generic method that reverses the elements in an array of type E objects, using a stack declared using the Stack<E> interface.
  • 23. Code Fragment 5.9: A test of the reverse method using two arrays.
  • 24. Code Fragment 5.8: A generic method that reverses the elements in an array of type E objects, using a stack declared using the Stack<E> interface.
  • 25. Code Fragment 5.9: A test of the reverse method using two arrays.
  • 26. MMaattcchhiinngg PPaarreenntthheesseess aanndd HHTTMMLL TTaaggss  TTwwoo rreellaatteedd aapppplliiccaattiioonnss ooff ssttaacckkss,,  tthhee ffiirrsstt ooff wwhhiicchh iiss ffoorr mmaattcchhiinngg ppaarreenntthheesseess  aanndd ggrroouuppiinngg ssyymmbboollss iinn aarriitthhmmeettiicc eexxpprreessssiioonnss..  AArriitthhmmeettiicc eexxpprreessssiioonnss ccaann ccoonnttaaiinn vvaarriioouuss ppaaiirrss ooff ggrroouuppiinngg ssyymmbboollss,, ssuucchh aass •• PPaarreenntthheesseess:: ""(("" aanndd ""))"" •• BBrraacceess:: ""{{"" aanndd ""}}"" •• BBrraacckkeettss:: ""[["" aanndd ""]]"" •• FFlloooorr ffuunnccttiioonn ssyymmbboollss:: "" ⌊⌊"" aanndd ""⌋⌋"" •• CCeeiilliinngg ffuunnccttiioonn ssyymmbboollss:: ""⌈⌈"" aanndd ""⌉⌉,,""  aanndd eeaacchh ooppeenniinngg ssyymmbbooll mmuusstt mmaattcchh wwiitthh iittss ccoorrrreessppoonnddiinngg cclloossiinngg ssyymmbbooll.. ::  [[((55 ++ xx)) −− ((yy ++ zz))]]..
  • 27. MMaattcchhiinngg PPaarreenntthheesseess aanndd HHTTMMLL TTaaggss TThhee ffoolllloowwiinngg eexxaammpplleess ffuurrtthheerr iilllluussttrraattee tthhiiss ccoonncceepptt:: •• CCoorrrreecctt:: (( ))(((( )))){{(([[(( ))]]))}} •• CCoorrrreecctt:: (((((( ))(((( )))){{(([[(( ))]]))}})))) •• IInnccoorrrreecctt:: ))(((( )))){{(([[(( ))]]))}} •• IInnccoorrrreecctt:: (({{[[]]))}} •• IInnccoorrrreecctt:: ((..
  • 28. AAnn AAllggoorriitthhmm ffoorr PPaarreenntthheesseess MMaattcchhiinngg  AAnn iimmppoorrttaanntt pprroobblleemm iinn pprroocceessssiinngg aarriitthhmmeettiicc eexxpprreessssiioonnss iiss ttoo mmaakkee ssuurree tthheeiirr ggrroouuppiinngg ssyymmbboollss mmaattcchh uupp ccoorrrreeccttllyy..  WWee ccaann uussee aa ssttaacckk SS ttoo ppeerrffoorrmm tthhee mmaattcchhiinngg ooff ggrroouuppiinngg ssyymmbboollss iinn aann aarriitthhmmeettiicc eexxpprreessssiioonn wwiitthh aa ssiinnggllee lleefftt--ttoo--rriigghhtt ssccaann..  TThhee aallggoorriitthhmm tteessttss tthhaatt lleefftt aanndd rriigghhtt ssyymmbboollss mmaattcchh uupp aanndd aallssoo tthhaatt tthhee lleefftt aanndd rriigghhtt ssyymmbboollss aarree bbootthh ooff tthhee ssaammee ttyyppee..  SSuuppppoossee wwee aarree ggiivveenn aa sseeqquueennccee XX == xx00xx11xx22……xxnn−−11,, wwhheerree eeaacchh xxii iiss aa ttookkeenn tthhaatt ccaann bbee aa ggrroouuppiinngg ssyymmbbooll,, aa vvaarriiaabbllee nnaammee,, aann aarriitthhmmeettiicc ooppeerraattoorr,, oorr aa nnuummbbeerr..  TThhee bbaassiicc iiddeeaa bbeehhiinndd cchheecckkiinngg tthhaatt tthhee ggrroouuppiinngg ssyymmbboollss iinn SS mmaattcchh ccoorrrreeccttllyy,,  iiss ttoo pprroocceessss tthhee ttookkeennss iinn XX iinn oorrddeerr..  EEaacchh ttiimmee wwee eennccoouunntteerr aann ooppeenniinngg ssyymmbbooll,, wwee ppuusshh tthhaatt ssyymmbbooll oonnttoo SS,,  aanndd eeaacchh ttiimmee wwee eennccoouunntteerr aa cclloossiinngg ssyymmbbooll,, wwee ppoopp tthhee ttoopp ssyymmbbooll ffrroomm tthhee ssttaacckk SS ((aassssuummiinngg SS iiss nnoott eemmppttyy)) aanndd wwee cchheecckk tthhaatt tthheessee ttwwoo ssyymmbboollss aarree ooff tthhee ssaammee ttyyppee..  IIff tthhee ssttaacckk iiss eemmppttyy aafftteerr wwee hhaavvee pprroocceesssseedd tthhee wwhhoollee sseeqquueennccee,, tthheenn tthhee ssyymmbboollss iinn XX mmaattcchh..  AAssssuummiinngg tthhaatt tthhee ppuusshh aanndd ppoopp ooppeerraattiioonnss aarree iimmpplleemmeenntteedd ttoo rruunn iinn ccoonnssttaanntt ttiimmee,, tthhiiss aallggoorriitthhmm rruunnss iinn OO((nn)),, tthhaatt iiss lliinneeaarr,, ttiimmee.. WWee ggiivvee aa ppsseeuuddoo--ccooddee ddeessccrriippttiioonn ooff tthhiiss aallggoorriitthhmm iinn CCooddee FFrraaggmmeenntt 55..1100..
  • 29. Code Fragment 5.10: Algorithm for matching grouping symbols in an arithmetic expression.
  • 30. MMaattcchhiinngg TTaaggss iinn aann HHTTMMLL DDooccuummeenntt  AAnnootthheerr aapppplliiccaattiioonn iinn wwhhiicchh mmaattcchhiinngg iiss iimmppoorrttaanntt iiss iinn tthhee vvaalliiddaattiioonn ooff HHTTMMLL ddooccuummeennttss..  HHTTMMLL iiss tthhee ssttaannddaarrdd ffoorrmmaatt ffoorr hhyyppeerrlliinnkkeedd ddooccuummeennttss oonn tthhee IInntteerrnneett.. II  nn aann HHTTMMLL ddooccuummeenntt,, ppoorrttiioonnss ooff tteexxtt aarree ddeelliimmiitteedd bbyy HHTTMMLL ttaaggss..  AA ssiimmppllee ooppeenniinngg HHTTMMLL ttaagg hhaass tthhee ffoorrmm "<<nnaammee>>" aanndd tthhee ccoorrrreessppoonnddiinngg cclloossiinngg ttaagg hhaass tthhee ffoorrmm "<<//nnaammee>>.." CCoommmmoonnllyy uusseedd HHTTMMLL ttaaggss iinncclluuddee •• bbooddyy:: ddooccuummeenntt bbooddyy •• hh11:: sseeccttiioonn hheeaaddeerr •• cceenntteerr:: cceenntteerr jjuussttiiffyy •• pp:: ppaarraaggrraapphh •• ooll:: nnuummbbeerreedd ((oorrddeerreedd)) lliisstt •• llii:: lliisstt iitteemm..  WWee sshhooww aa ssaammppllee HHTTMMLL ddooccuummeenntt aanndd aa ppoossssiibbllee rreennddeerriinngg iinn FFiigguurree 55..33..
  • 31. Figure 5.3: Illustrating HTML tags. (a) An HTML document; (b) its rendering.
  • 32. Code Fragment 5.11: A complete Java program for testing if an HTML document has fully matching tags. (Continues in Code Fragment 5.12.)
  • 33. WWhhaatt iiss QQuueeuuee??  QQuueeuuee iiss aa ddaattaa ssttrruuccttuurree iinn wwhhiicchh iinnsseerrttiioonn iiss ddoonnee aatt oonnee eenndd ((FFrroonntt)),, wwhhiillee ddeelleettiioonn iiss ppeerrffoorrmmeedd aatt tthhee ootthheerr eenndd ((RReeaarr))  CCoonnttrraasstt wwiitthh ssttaacckk,, wwhheerree iinnsseerrttiioonn aanndd ddeelleettiioonn aatt oonnee aanndd tthhee ssaammee eenndd  IItt iiss FFiirrsstt IInn,, FFiirrsstt OOuutt ((FFIIFFOO)) ssttrruuccttuurree  FFoorr eexxaammppllee,, ccuussttoommeerrss ssttaannddiinngg iinn aa cchheecckk--oouutt lliinnee iinn aa ssttoorree,, tthhee ffiirrsstt ccuussttoommeerr iinn iiss tthhee ffiirrsstt ccuussttoommeerr sseerrvveedd..
  • 34. QQuueeuuee ooppeerraattiioonnss  EEnnqquueeuuee:: iinnsseerrtt aann eelleemmeenntt aatt tthhee rreeaarr ooff tthhee lliisstt  DDeeqquueeuuee:: ddeelleettee tthhee eelleemmeenntt aatt tthhee ffrroonntt ooff tthhee lliisstt Insert (Enqueue) Remove (Dequeue) front rear
  • 35. BBuuiillddiinngg aa QQuueeuuee SStteepp--bbyy--SStteepp  TThheerree aarree sseevveerraall ddiiffffeerreenntt aallggoorriitthhmmss ttoo iimmpplleemmeenntt EEnnqquueeuuee aanndd DDeeqquueeuuee  EEnnqquueeuuiinngg  TThhee ffrroonntt iinnddeexx iiss aallwwaayyss ffiixxeedd  TThhee rreeaarr iinnddeexx mmoovveess ffoorrwwaarrdd iinn tthhee aarrrraayy rear 3 front Enqueue(3) 3 6 front rear Enqueue(6) 3 6 9 front rear Enqueue(9)
  • 36. BBuuiillddiinngg aa QQuueeuuee SStteepp--bbyy--SStteepp  DDeeqquueeuuiinngg  TThhee eelleemmeenntt aatt tthhee ffrroonntt ooff tthhee qquueeuuee iiss rreemmoovveedd  MMoovvee aallll tthhee eelleemmeennttss aafftteerr iitt bbyy oonnee ppoossiittiioonn 6 9 front rear Dequeue() rear 9 front rear = -1 front Dequeue() Dequeue()
  • 37. TThhee QQuueeuuee AAbbssttrraacctt DDaattaa TTyyppee  FFoorrmmaallllyy,, tthhee qquueeuuee aabbssttrraacctt ddaattaa ttyyppee ddeeffiinneess aa ccoolllleeccttiioonn tthhaatt kkeeeeppss oobbjjeeccttss iinn aa sseeqquueennccee,, wwhheerree  eelleemmeenntt aacccceessss aanndd ddeelleettiioonn aarree rreessttrriicctteedd ttoo tthhee ffiirrsstt eelleemmeenntt iinn tthhee sseeqquueennccee,, tthhee ffrroonntt ooff tthhee qquueeuuee,,  aanndd eelleemmeenntt iinnsseerrttiioonn iiss rreessttrriicctteedd ttoo tthhee eenndd ooff tthhee sseeqquueennccee,, tthhee rreeaarr ooff tthhee qquueeuuee..  TThhiiss rreessttrriiccttiioonn eennffoorrcceess tthhee rruullee tthhaatt iitteemmss aarree iinnsseerrtteedd aanndd ddeelleetteedd iinn aa qquueeuuee aaccccoorrddiinngg ttoo tthhee ffiirrsstt--iinn ffiirrsstt--oouutt ((FFIIFFOO)) pprriinncciippllee..  TThhee qquueeuuee aabbssttrraacctt ddaattaa ttyyppee ((AADDTT)) ssuuppppoorrttss tthhee ffoolllloowwiinngg ttwwoo ffuunnddaammeennttaall mmeetthhooddss::  eennqquueeuuee((ee)):: IInnsseerrtt eelleemmeenntt ee aatt tthhee rreeaarr ooff tthhee qquueeuuee..  ddeeqquueeuuee(()):: RReemmoovvee aanndd rreettuurrnn ffrroomm tthhee qquueeuuee tthhee oobbjjeecctt aatt tthhee ffrroonntt;;  aann eerrrroorr ooccccuurrss iiff tthhee qquueeuuee iiss eemmppttyy..  AAddddiittiioonnaallllyy,, ssiimmiillaarr ttoo tthhee ccaassee wwiitthh tthhee SSttaacckk AADDTT,, tthhee qquueeuuee AADDTT iinncclluuddeess tthhee ffoolllloowwiinngg ssuuppppoorrttiinngg mmeetthhooddss::  ssiizzee(()):: RReettuurrnn tthhee nnuummbbeerr ooff oobbjjeeccttss iinn tthhee qquueeuuee..  iissEEmmppttyy(()):: RReettuurrnn aa BBoooolleeaann vvaalluuee tthhaatt iinnddiiccaatteess wwhheetthheerr tthhee qquueeuuee iiss eemmppttyy..  ffrroonntt(()):: RReettuurrnn,, bbuutt ddoo nnoott rreemmoovvee,, tthhee ffrroonntt oobbjjeecctt iinn tthhee qquueeuuee;;  aann eerrrroorr ooccccuurrss iiff tthhee qquueeuuee iiss eemmppttyy..
  • 38. TThhee QQuueeuuee AAbbssttrraacctt DDaattaa TTyyppee  EExxaammppllee 55..44:: TThhee ffoolllloowwiinngg ttaabbllee sshhoowwss aa sseerriieess ooff qquueeuuee ooppeerraattiioonnss aanndd tthheeiirr eeffffeeccttss oonn aann iinniittiiaallllyy eemmppttyy qquueeuuee QQ ooff iinntteeggeerr oobbjjeeccttss.. FFoorr ssiimmpplliicciittyy,, wwee uussee iinntteeggeerrss iinnsstteeaadd ooff iinntteeggeerr oobbjjeeccttss aass aarrgguummeennttss ooff tthhee ooppeerraattiioonnss.. OOppeerraattiioonn OOuuttppuutt ffrroonntt ←← QQ ←← rreeaarr eennqquueeuuee((55)) eennqquueeuuee((33)) ddeeqquueeuuee(( )) eennqquueeuuee((77)) ddeeqquueeuuee(( )) ffrroonntt(( )) ddeeqquueeuuee(( )) ddeeqquueeuuee(( )) iissEEmmppttyy(( )) eennqquueeuuee((99)) eennqquueeuuee((77)) ssiizzee(()) eennqquueeuuee((33)) eennqquueeuuee((55)) ddeeqquueeuuee(( )) -- -- 55 -- 33 77 77 "eerrrroorr" ttrruuee -- -- 22 -- -- 99 ((55)) ((55,, 33)) ((33)) ((33,, 77)) ((77)) ((77)) (( )) (( )) (( )) ((99)) ((99,, 77)) ((99,, 77)) ((99,, 77,, 33)) ((99,, 77,, 33,, 55)) ((77,, 33,, 55))
  • 39. TThhee QQuueeuuee AAbbssttrraacctt DDaattaa TTyyppee  EExxaammppllee AApppplliiccaattiioonnss  TThheerree aarree sseevveerraall ppoossssiibbllee aapppplliiccaattiioonnss ffoorr qquueeuueess..  SSttoorreess,,  tthheeaatteerrss,,  rreesseerrvvaattiioonn cceenntteerrss,,  aanndd ootthheerr ssiimmiillaarr sseerrvviicceess ttyyppiiccaallllyy pprroocceessss ccuussttoommeerr rreeqquueessttss aaccccoorrddiinngg ttoo tthhee FFIIFFOO pprriinncciippllee..  AA qquueeuuee wwoouulldd tthheerreeffoorree bbee aa llooggiiccaall cchhooiiccee ffoorr aa ddaattaa ssttrruuccttuurree ttoo hhaannddllee ttrraannssaaccttiioonn pprroocceessssiinngg ffoorr ssuucchh aapppplliiccaattiioonnss..  FFoorr eexxaammppllee,, iitt wwoouulldd bbee aa nnaattuurraall cchhooiiccee ffoorr hhaannddlliinngg ccaallllss ttoo tthhee rreesseerrvvaattiioonn cceenntteerr ooff aann aaiirrlliinnee oorr ttoo tthhee bbooxx ooffffiiccee ooff aa tthheeaatteerr..
  • 40. AA QQuueeuuee IInntteerrffaaccee iinn JJaavvaa  AA JJaavvaa iinntteerrffaaccee ffoorr tthhee qquueeuuee AADDTT iiss ggiivveenn iinn CCooddee FFrraaggmmeenntt 55..1133..  TThhiiss ggeenneerriicc iinntteerrffaaccee ssppeecciiffiieess tthhaatt oobbjjeeccttss ooff aarrbbiittrraarryy oobbjjeecctt ttyyppeess ccaann bbee iinnsseerrtteedd iinnttoo tthhee qquueeuuee..  TThhuuss,, wwee ddoonn''tt hhaavvee ttoo uussee eexxpplliicciitt ccaassttiinngg wwhheenn rreemmoovviinngg eelleemmeennttss..  NNoottee tthhaatt tthhee ssiizzee aanndd iissEEmmppttyy mmeetthhooddss hhaavvee tthhee ssaammee mmeeaanniinngg aass tthheeiirr ccoouunntteerrppaarrttss iinn tthhee SSttaacckk AADDTT..  TThheessee ttwwoo mmeetthhooddss,, aass wweellll aass tthhee ffrroonntt mmeetthhoodd,, aarree kknnoowwnn aass aacccceessssoorr mmeetthhooddss,, ffoorr tthheeyy rreettuurrnn aa vvaalluuee aanndd ddoo nnoott cchhaannggee tthhee ccoonntteennttss ooff tthhee ddaattaa ssttrruuccttuurree..
  • 41. Code Fragment 5.13: Interface Queue documented with comments in Javadoc style.
  • 42. A Simple AArrrraayy--BBaasseedd QQuueeuuee IImmpplleemmeennttaattiioonn  WWee pprreesseenntt aa ssiimmppllee rreeaalliizzaattiioonn ooff aa qquueeuuee bbyy mmeeaannss ooff aann aarrrraayy,, QQ,, ooff ffiixxeedd ccaappaacciittyy,, ssttoorriinngg iittss eelleemmeennttss..  SSiinnccee tthhee mmaaiinn rruullee wwiitthh tthhee qquueeuuee AADDTT iiss tthhaatt wwee iinnsseerrtt aanndd ddeelleettee oobbjjeeccttss aaccccoorrddiinngg ttoo tthhee FFIIFFOO pprriinncciippllee,, wwee mmuusstt ddeecciiddee hhooww wwee aarree ggooiinngg ttoo kkeeeepp ttrraacckk ooff tthhee ffrroonntt aanndd rreeaarr ooff tthhee qquueeuuee..  OOnnee ppoossssiibbiilliittyy iiss ttoo aaddaapptt tthhee aapppprrooaacchh wwee uusseedd ffoorr tthhee ssttaacckk iimmpplleemmeennttaattiioonn,,  lleettttiinngg QQ[[00]] bbee tthhee ffrroonntt ooff tthhee qquueeuuee aanndd tthheenn lleettttiinngg tthhee qquueeuuee ggrrooww ffrroomm tthheerree..  TThhiiss iiss nnoott aann eeffffiicciieenntt ssoolluuttiioonn,, hhoowweevveerr,, ffoorr iitt rreeqquuiirreess tthhaatt wwee mmoovvee aallll tthhee eelleemmeennttss ffoorrwwaarrdd oonnee aarrrraayy cceellll eeaacchh ttiimmee wwee ppeerrffoorrmm aa ddeeqquueeuuee ooppeerraattiioonn..  SSuucchh aann iimmpplleemmeennttaattiioonn wwoouulldd tthheerreeffoorree ttaakkee OO((nn)) ttiimmee ttoo ppeerrffoorrmm tthhee ddeeqquueeuuee mmeetthhoodd,, wwhheerree nn iiss tthhee ccuurrrreenntt nnuummbbeerr ooff oobbjjeeccttss iinn tthhee qquueeuuee..  IIff wwee wwaanntt ttoo aacchhiieevvee ccoonnssttaanntt ttiimmee ffoorr eeaacchh qquueeuuee mmeetthhoodd,, wwee nneeeedd aa ddiiffffeerreenntt aapppprrooaacchh,, bbuutt tthhaatt aapppprrooaacchh mmaayy hhaavvee iittss oowwnn ddeemmeerriittss..
  • 43. Using an Array iinn aa CCiirrccuullaarr WWaayy  TToo aavvooiidd mmoovviinngg oobbjjeeccttss oonnccee tthheeyy aarree ppllaacceedd iinn QQ,,  wwee ddeeffiinnee ttwwoo vvaarriiaabblleess ff aanndd rr,, wwhhiicchh hhaavvee tthhee ffoolllloowwiinngg mmeeaanniinnggss::  ff iiss aann iinnddeexx ttoo tthhee cceellll ooff QQ ssttoorriinngg tthhee ffiirrsstt eelleemmeenntt ooff tthhee qquueeuuee ((nneexxtt ccaannddiiddaattee ttoo bbee rreemmoovveedd bbyy aa ddeeqquueeuuee ooppeerraattiioonn)),,  ff == rr qquueeuuee iiss eemmppttyy..  rr iiss aann iinnddeexx ttoo tthhee nneexxtt aavvaaiillaabbllee aarrrraayy cceellll iinn QQ..  IInniittiiaallllyy,, wwee aassssiiggnn ff == rr == 00,, wwhhiicchh iinnddiiccaatteess tthhaatt tthhee qquueeuuee iiss eemmppttyy..  WWhheenn wwee rreemmoovvee aann eelleemmeenntt ffrroomm tthhee ffrroonntt ooff tthhee qquueeuuee,, iinnccrreemmeenntt ff ttoo iinnddeexx tthhee nneexxtt cceellll..  AAddddiinngg aann eelleemmeenntt,, wwee ssttoorree iitt iinn cceellll QQ[[rr]] aanndd iinnccrreemmeenntt rr ttoo iinnddeexx tthhee nneexxtt aavvaaiillaabbllee cceellll iinn QQ..  TThhiiss sscchheemmee aalllloowwss uuss ttoo iimmpplleemmeenntt mmeetthhooddss ffrroonntt,, eennqquueeuuee,, aanndd ddeeqquueeuuee iinn ccoonnssttaanntt ttiimmee,, tthhaatt iiss,, OO((11)) ttiimmee..  HHoowweevveerr,, tthheerree iiss ssttiillll aa pprroobblleemm wwiitthh tthhiiss aapppprrooaacchh..  what happens if we repeatedly enqueue and dequeue a single element N different times.  WWee wwoouulldd hhaavvee ff == rr == NN.. IIff wwee wweerree tthheenn ttoo ttrryy ttoo iinnsseerrtt tthhee eelleemmeenntt jjuusstt oonnee mmoorree ttiimmee,, wwee wwoouulldd ggeett aann aarrrraayy--oouutt--ooff--bboouunnddss eerrrroorr ((ssiinnccee tthhee NN vvaalliidd llooccaattiioonnss iinn QQ aarree ffrroomm QQ[[00]] ttoo QQ[[NN −− 11]])),, eevveenn tthhoouugghh tthheerree iiss pplleennttyy ooff rroooomm iinn tthhee qquueeuuee iinn tthhiiss ccaassee..  TToo aavvooiidd tthhiiss pprroobblleemm aanndd bbee aabbllee ttoo uuttiilliizzee aallll ooff tthhee aarrrraayy QQ,, wwee lleett tthhee ff aanndd rr iinnddiicceess ""wwrraapp aarroouunndd"" tthhee eenndd ooff QQ..  TThhaatt iiss,, wwee nnooww vviieeww QQ aass aa ""cciirrccuullaarr aarrrraayy"" tthhaatt ggooeess ffrroomm QQ[[00]] ttoo QQ[[NN −− 11]] aanndd tthheenn iimmmmeeddiiaatteellyy bbaacckk ttoo QQ[[00]] aaggaaiinn.. ((SSeeee FFiigguurree 55..44..))
  • 44. Figure 5.4: Using array Q in a circular fashion: (a) the "normal" configuration with f ≤ r; (b) the "wrapped around" configuration (b) with r < f. The cells storing queue elements are highlighted.
  • 45. Using tthhee MMoodduulloo OOppeerraattoorr ttoo IImmpplleemmeenntt aa CCiirrccuullaarr AArrrraayy  IImmpplleemmeennttiinngg tthhiiss cciirrccuullaarr vviieeww ooff QQ iiss aaccttuuaallllyy pprreettttyy eeaassyy..  EEaacchh ttiimmee wwee iinnccrreemmeenntt ff oorr rr,, wwee ccoommppuuttee tthhiiss iinnccrreemmeenntt aass ""((ff ++ 11)) mmoodd NN"" oorr ""((rr ++ 11)) mmoodd NN,,"" rreessppeeccttiivveellyy..  ""mmoodd"" iiss tthhee mmoodduulloo ooppeerraattoorr,, wwhhiicchh iiss ccoommppuutteedd bbyy ttaakkiinngg tthhee rreemmaaiinnddeerr aafftteerr aann iinntteeggrraall ddiivviissiioonn..  FFoorr eexxaammppllee,, 1144 ddiivviiddeedd bbyy 44 iiss 33 wwiitthh rreemmaaiinnddeerr 22,, ssoo 1144 mmoodd 44 == 22..  JJaavvaa uusseess ""%%"" ttoo ddeennoottee tthhee mmoodduulloo ooppeerraattoorr.. BByy uussiinngg tthhee mmoodduulloo ooppeerraattoorr,, wwee ccaann vviieeww QQ aass aa cciirrccuullaarr aarrrraayy aanndd iimmpplleemmeenntt eeaacchh qquueeuuee mmeetthhoodd iinn aa ccoonnssttaanntt aammoouunntt ooff ttiimmee ((tthhaatt iiss,, OO((11)) ttiimmee)).. WWee ddeessccrriibbee hhooww ttoo uussee tthhiiss aapppprrooaacchh ttoo iimmpplleemmeenntt aa qquueeuuee iinn CCooddee FFrraaggmmeenntt 55..1144..
  • 46. Code Fragment 5.14: Implementation of a queue using a circular array. The implementation uses the modulo operator to "wrap" indices around the end of the array and it also includes two instance variables, f and r, which index the front of the queue and first empty cell after the rear of the queue respectively.
  • 47. Using tthhee MMoodduulloo OOppeerraattoorr ttoo IImmpplleemmeenntt aa CCiirrccuullaarr AArrrraayy  TThhee iimmpplleemmeennttaattiioonn aabboovvee ccoonnttaaiinnss aann iimmppoorrttaanntt ddeettaaiill,, wwhhiicchh mmiigghhtt bbee mmiisssseedd aatt ffiirrsstt..  CCoonnssiiddeerr tthhee ssiittuuaattiioonn tthhaatt ooccccuurrss iiff wwee eennqquueeuuee NN oobbjjeeccttss iinnttoo QQ wwiitthhoouutt ddeeqquueeuuiinngg aannyy ooff tthheemm.. WWee wwoouulldd hhaavvee ff == rr,, wwhhiicchh iiss tthhee ssaammee ccoonnddiittiioonn tthhaatt ooccccuurrss wwhheenn tthhee qquueeuuee iiss eemmppttyy..  HHeennccee,, wwee wwoouulldd nnoott bbee aabbllee ttoo tteellll tthhee ddiiffffeerreennccee bbeettwweeeenn aa ffuullll qquueeuuee aanndd aann eemmppttyy oonnee iinn tthhiiss ccaassee..  FFoorrttuunnaatteellyy,, tthhiiss iiss nnoott aa bbiigg pprroobblleemm,, aanndd aa nnuummbbeerr ooff wwaayyss ffoorr ddeeaalliinngg wwiitthh iitt eexxiisstt..  TThhee ssoolluuttiioonn wwee ddeessccrriibbee hheerree iiss ttoo iinnssiisstt tthhaatt QQ ccaann nneevveerr hhoolldd mmoorree tthhaann NN −− 11 oobbjjeeccttss..  TThhiiss ssiimmppllee rruullee ffoorr hhaannddlliinngg aa ffuullll qquueeuuee ttaakkeess ccaarree ooff tthhee ffiinnaall pprroobblleemm wwiitthh oouurr iimmpplleemmeennttaattiioonn,, aanndd lleeaaddss ttoo tthhee ppsseeuuddoo--ccooddeedd ddeessccrriippttiioonnss ooff tthhee qquueeuuee mmeetthhooddss ggiivveenn iinn CCooddee FFrraaggmmeenntt 55..1144..  NNoottee oouurr iinnttrroodduuccttiioonn ooff aann iimmpplleemmeennttaattiioonn--ssppeecciiffiicc eexxcceeppttiioonn,, ccaalllleedd FFuullllQQuueeuueeEExxcceeppttiioonn,, ttoo ssiiggnnaall tthhaatt nnoo mmoorree eelleemmeennttss ccaann bbee iinnsseerrtteedd iinn tthhee qquueeuuee..  AAllssoo nnoottee tthhee wwaayy wwee ccoommppuuttee tthhee ssiizzee ooff tthhee qquueeuuee bbyy mmeeaannss ooff tthhee eexxpprreessssiioonn ((NN −− ff ++ rr)) mmoodd NN,, wwhhiicchh ggiivveess tthhee ccoorrrreecctt rreessuulltt bbootthh iinn tthhee ""nnoorrmmaall"" ccoonnffiigguurraattiioonn ((wwhheenn ff ≤≤ rr)) aanndd iinn tthhee ""wwrraappppeedd aarroouunndd"" ccoonnffiigguurraattiioonn ((wwhheenn rr << ff))..  TThhee JJaavvaa iimmpplleemmeennttaattiioonn ooff aa qquueeuuee bbyy mmeeaannss ooff aann aarrrraayy iiss ssiimmiillaarr ttoo tthhaatt ooff aa ssttaacckk,, aanndd iiss lleefftt aass aann eexxeerrcciissee ((PP--55..44))..  TTaabbllee 55..22 sshhoowwss tthhee rruunnnniinngg ttiimmeess ooff mmeetthhooddss iinn aa rreeaalliizzaattiioonn ooff aa qquueeuuee bbyy aann aarrrraayy.. AAss wwiitthh oouurr aarrrraayy--bbaasseedd ssttaacckk iimmpplleemmeennttaattiioonn,, eeaacchh ooff tthhee qquueeuuee mmeetthhooddss iinn tthhee aarrrraayy rreeaalliizzaattiioonn eexxeeccuutteess aa ccoonnssttaanntt nnuummbbeerr ooff ssttaatteemmeennttss iinnvvoollvviinngg aarriitthhmmeettiicc ooppeerraattiioonnss,, ccoommppaarriissoonnss,, aanndd aassssiiggnnmmeennttss.. TThhuuss,, eeaacchh mmeetthhoodd iinn tthhiiss iimmpplleemmeennttaattiioonn rruunnss iinn OO((11)) ttiimmee..
  • 48. TTaabbllee 55..22:: PPeerrffoorrmmaannccee ooff aa qquueeuuee rreeaalliizzeedd bbyy aann aarrrraayy  TThhee ssppaaccee uussaaggee iiss OO((NN)),, wwhheerree NN iiss tthhee ssiizzee ooff tthhee aarrrraayy,, ddeetteerrmmiinneedd aatt tthhee ttiimmee tthhee qquueeuuee iiss ccrreeaatteedd.. NNoottee tthhaatt tthhee ssppaaccee uussaaggee iiss iinnddeeppeennddeenntt ffrroomm tthhee nnuummbbeerr nn << NN ooff eelleemmeennttss tthhaatt aarree aaccttuuaallllyy iinn tthhee qquueeuuee.. MMeetthhoodd TTiimmee SSiizzee iissEEmmppttyy ffrroonntt eennqquueeuuee ddeeqquueeuuee OO((11)) OO((11)) OO((11)) OO((11)) OO((11)) Problem is the capacity of the queue to be some fixed value. In a real application, we may actually need more or less queue capacity than this, but if we have a good capacity estimate, then the array-based implementation is quite efficient.
  • 49. Implementing aa QQuueeuuee wwiitthh aa GGeenneerriicc LLiinnkkeedd LLiisstt WWee ccaann eeffffiicciieennttllyy iimmpplleemmeenntt tthhee qquueeuuee AADDTT uussiinngg aa ggeenneerriicc ssiinnggllyy lliinnkkeedd lliisstt..  FFoorr eeffffiicciieennccyy rreeaassoonnss,,  tthhee ffrroonntt ooff tthhee qquueeuuee ttoo bbee aatt tthhee hheeaadd ooff tthhee lliisstt,,  aanndd tthhee rreeaarr ooff tthhee qquueeuuee ttoo bbee aatt tthhee ttaaiill ooff tthhee lliisstt..  IInn tthhiiss wwaayy,, wwee rreemmoovvee ffrroomm tthhee hheeaadd aanndd iinnsseerrtt aatt tthhee ttaaiill.. ((WWhhyy wwoouulldd iitt bbee bbaadd ttoo iinnsseerrtt aatt tthhee hheeaadd aanndd rreemmoovvee aatt tthhee ttaaiill??)) NNoottee tthhaatt wwee nneeeedd ttoo mmaaiinnttaaiinn rreeffeerreenncceess ttoo bbootthh tthhee hheeaadd aanndd ttaaiill nnooddeess ooff tthhee lliisstt.. RRaatthheerr tthhaann ggoo iinnttoo eevveerryy ddeettaaiill ooff tthhiiss iimmpplleemmeennttaattiioonn,, wwee ssiimmppllyy ggiivvee aa JJaavvaa iimmpplleemmeennttaattiioonn ffoorr tthhee ffuunnddaammeennttaall qquueeuuee mmeetthhooddss iinn CCooddee FFrraaggmmeenntt 55..1155..
  • 50. CCooddee FFrraaggmmeenntt 55..1155:: MMeetthhooddss eennqquueeuuee aanndd ddeeqquueeuuee iinn tthhee iimmpplleemmeennttaattiioonn ooff tthhee qquueeuuee AADDTT bbyy mmeeaannss ooff aa ssiinnggllyy lliinnkkeedd lliisstt,, uussiinngg nnooddeess ffrroomm ccllaassss NNooddee ooff CCooddee FFrraaggmmeenntt 55..66.. Each of the methods of the singly linked list implementation of the queue ADT runs in O(1) time. We also avoid the need to specify a maximum size for the queue, but this benefit comes at the expense of increasing the amount of space used per element. Still, the methods in the singly linked list queue implementation are more complicated than we might like, for we must take extra care in how we deal with special cases where the queue is empty before an enqueue or where the queue becomes empty after a dequeue.
  • 51. RRoouunndd RRoobbiinn SScchheedduulleerrss  AA ppooppuullaarr uussee ooff tthhee qquueeuuee ddaattaa ssttrruuccttuurree iiss ttoo iimmpplleemmeenntt aa rroouunndd rroobbiinn sscchheedduulleerr,, wwhheerree  wwee iitteerraattee tthhrroouugghh aa ccoolllleeccttiioonn ooff eelleemmeennttss iinn aa cciirrccuullaarr ffaasshhiioonn aanndd ""sseerrvviiccee"" eeaacchh eelleemmeenntt bbyy ppeerrffoorrmmiinngg aa ggiivveenn aaccttiioonn oonn iitt..  SSuucchh aa sscchheedduullee iiss uusseedd,,  ffoorr eexxaammppllee,, ttoo ffaaiirrllyy aallllooccaattee aa rreessoouurrccee tthhaatt mmuusstt bbee sshhaarreedd bbyy aa ccoolllleeccttiioonn ooff cclliieennttss..  FFoorr iinnssttaannccee,, wwee ccaann uussee aa rroouunndd rroobbiinn sscchheedduulleerr ttoo aallllooccaattee aa sslliiccee ooff CCPPUU ttiimmee ttoo vvaarriioouuss aapppplliiccaattiioonnss rruunnnniinngg ccoonnccuurrrreennttllyy oonn aa ccoommppuutteerr..  WWee ccaann iimmpplleemmeenntt aa rroouunndd rroobbiinn sscchheedduulleerr uussiinngg aa qquueeuuee,, QQ,, bbyy rreeppeeaatteeddllyy ppeerrffoorrmmiinngg tthhee ffoolllloowwiinngg sstteeppss ((sseeee FFiigguurree 55..55)):: 11.. ee ←← QQ..ddeeqquueeuuee(()) 22.. SSeerrvviiccee eelleemmeenntt ee 33.. QQ..eennqquueeuuee((ee))
  • 52. Figure 5.5: The three iterative steps for using a queue to implement a round robin scheduler.
  • 53. TThhee JJoosseepphhuuss PPrroobblleemm  IInn tthhee cchhiillddrreenn''ss ggaammee ""hhoott ppoottaattoo,,"" aa ggrroouupp ooff nn cchhiillddrreenn ssiitt iinn aa cciirrccllee ppaassssiinngg aann oobbjjeecctt,, ccaalllleedd tthhee ""ppoottaattoo,,"" aarroouunndd tthhee cciirrccllee.. TThhee ppoottaattoo bbeeggiinnss wwiitthh aa ssttaarrttiinngg cchhiilldd iinn tthhee cciirrccllee,, aanndd tthhee cchhiillddrreenn ccoonnttiinnuuee ppaassssiinngg tthhee ppoottaattoo uunnttiill aa lleeaaddeerr rriinnggss aa bbeellll,, aatt wwhhiicchh ppooiinntt tthhee cchhiilldd hhoollddiinngg tthhee ppoottaattoo mmuusstt lleeaavvee tthhee ggaammee aafftteerr hhaannddiinngg tthhee ppoottaattoo ttoo tthhee nneexxtt cchhiilldd iinn tthhee cciirrccllee.. AAfftteerr tthhee sseelleecctteedd cchhiilldd lleeaavveess,, tthhee ootthheerr cchhiillddrreenn cclloossee uupp tthhee cciirrccllee.. TThhiiss pprroocceessss iiss tthheenn ccoonnttiinnuueedd uunnttiill tthheerree iiss oonnllyy oonnee cchhiilldd rreemmaaiinniinngg,, wwhhoo iiss ddeeccllaarreedd tthhee wwiinnnneerr.. IIff tthhee lleeaaddeerr aallwwaayyss uusseess tthhee ssttrraatteeggyy ooff rriinnggiinngg tthhee bbeellll aafftteerr tthhee ppoottaattoo hhaass bbeeeenn ppaasssseedd kk ttiimmeess,, ffoorr ssoommee ffiixxeedd vvaalluuee kk,, tthheenn ddeetteerrmmiinniinngg tthhee wwiinnnneerr ffoorr aa ggiivveenn lliisstt ooff cchhiillddrreenn iiss kknnoowwnn aass tthhee JJoosseepphhuuss pprroobblleemm..
  • 54. Solving tthhee JJoosseepphhuuss PPrroobblleemm UUssiinngg aa QQuueeuuee  WWee ccaann ssoollvvee tthhee JJoosseepphhuuss pprroobblleemm ffoorr aa ccoolllleeccttiioonn ooff nn eelleemmeennttss uussiinngg aa qquueeuuee,, bbyy aassssoocciiaattiinngg tthhee ppoottaattoo wwiitthh tthhee eelleemmeenntt aatt tthhee ffrroonntt ooff tthhee qquueeuuee aanndd ssttoorriinngg eelleemmeennttss iinn tthhee qquueeuuee aaccccoorrddiinngg ttoo tthheeiirr oorrddeerr aarroouunndd tthhee cciirrccllee.. TThhuuss,, ppaassssiinngg tthhee ppoottaattoo iiss eeqquuiivvaalleenntt ttoo ddeeqquueeuuiinngg aann eelleemmeenntt aanndd iimmmmeeddiiaatteellyy eennqquueeuuiinngg iitt aaggaaiinn.. AAfftteerr tthhiiss pprroocceessss hhaass bbeeeenn ppeerrffoorrmmeedd kk ttiimmeess,, wwee rreemmoovvee tthhee ffrroonntt eelleemmeenntt bbyy ddeeqquueeuuiinngg iitt ffrroomm tthhee qquueeuuee aanndd ddiissccaarrddiinngg iitt.. WWee sshhooww aa ccoommpplleettee JJaavvaa pprrooggrraamm ffoorr ssoollvviinngg tthhee JJoosseepphhuuss pprroobblleemm uussiinngg tthhiiss aapppprrooaacchh iinn CCooddee FFrraaggmmeenntt 55..1166,, wwhhiicchh ddeessccrriibbeess aa ssoolluuttiioonn tthhaatt rruunnss iinn OO((nnkk)) ttiimmee.. ((WWee ccaann ssoollvvee tthhiiss pprroobblleemm ffaasstteerr uussiinngg tteecchhnniiqquueess bbeeyyoonndd tthhee ssccooppee ooff tthhiiss bbooookk..))
  • 55. Code Fragment 5.16: A complete Java program for solving the Josephus problem using a queue. Class NodeQueue is shown in Code Fragment 5.15.