DS Module_1(2)
DS Module_1(2)
MODULE1
STACKANDQUEUE
1.
1 I
ntr
oduct
iont
odi
ff
erentDat
aSt
ruct
ures
Adatastructureisamethodf oror
gani
zi
ngandst
ori
ngdat
awhi
chwoul
dal
l
ow
ef
fi
cientdataretr
iev
alandusage.
DataStruct
ures i
saboutrenderi
ngdat
ael
ement
sint
ermsofsomer
elat
ionshi
p,
forbet
terorgani
zat
ionandstorage.
DataStruct
uresar
est
ructur
espr
ogrammedt
ost
oreor
der
eddat
a,sot
hatv
ari
ous
operat
ionscanbeper
formedoniteasi
l
y.
1.
1.1 Ef
fi
ciencyofal
gor
it
hms,
compl
exi
tyandbi
gOnot
ati
on
Algori
thm :Analgori
thm isacl ear
lyspeci
fi
edsetofsi mpl
einst
ructi
onsto be
fol
lowedtosol
veapr obl
em.Itisaf i
nit
esetofinst
ruct
ionsorl
ogi
c,writ
teni
norder
toaccompli
shacertai
npredef
inedtask.
1.
1.1.
1Ef
fi
ciencyofal
gor
it
hm
Oncean al
gori
thm isgiv
en f
oraprobl
em and deci
ded t
o becor
rect
,thenext
i
mportantst
epistodeter
minehowmuchi
nthewayofresour
ces,
suchast
imeorspace,
the
al
gor
it
hm willr
equi
re.
Anal gor
it
hm issaidt obeeffi
cientandf
astifi
ttakeslesst
imetoexecut
eand
consumesl essmemor yspace.Theperf
ormanceofanal
gori
thm i
smeasur
edonthebasi
s
ofthefol
lowingproper
ti
es:
i. SpaceCompl exi
ty
i
i
. Ti
meCompl
exi
ty
1.
1.1.
2Compl
exi
ty
1)SpaceCompl
exi
ty: Thespacecompl
exi
tyofapr
ogr
am i
stheamountofmemor
yit
needstorunt
ocompl et
ioni
.e,duri
ngthecourseofi
tsexecut
ion.Spacecompl
exit
ymust
betakenseri
ouslyformulti
-usersystemsandi nsit
uati
onswher eli
mitedmemoryis
avai
labl
e.Analgor
it
hm general
lyrequi
resspacefori
nstr
ucti
ons,dataandenvi
ronment
.
Thespaceneededbytheprogramscanbesummedupas
a.Af i
xedpartthati
sindependentoft hecharacter
ist
ics(eg.number,si
ze)ofthe
i
nputsandout put
s.Thi
spar tty
picall
yincludestheinst
ructi
onspace(spacefor
code),spaceforsi
mplev ar
iabl
es( alsocall
edaggregate),spacef
orconstants,
etc.
b.Av ar
iabl
epartthatconsist
soft hespaceneededbycomponentvari
ableswhose
si
zei sdependentont hepart
icularprobl
em inst
ancebei
ngsolved,thespace
needed byreferenced var
iabl
esand t herecursi
onstackspace( dependson
i
nstancecharacter
ist
ics)
Thespacer
equi
rementS(
P)ofanypr
ogr
am Pmayt
her
efor
ebewr
it
tenas
S(
P)=c+Sp(
inst
ancechar
act
eri
sti
cs)
wher
eci
saconst
ant
.
Esti
mationofSp( i
nst
ancechar
acter
ist
ics)i
sconcent
rat
edforanyprobl
em forwhich
fi
rst
,whichinst
ancechar
act
eri
sti
cstobeusedasameasur eoft
hespacerequi
rements
i
sdet er
mined.
2)TimeCompl exi
ty:Thet i
mecompl exit
yofapr ogr
am i
stheamountofcomputerti
meit
needstorunt ocompl et
ion.ThetimeT( P),t
akenbyapr ogr
am Pisthesum of the
compilet
imeandt her un(execut
ion)time.Thecompilet
imedoesnotdependont he
i
nstancecharact
eri
sti
csandso, t
her unti
meofapr ogr
am i
sconcent
rat
edupon.Thi
srun
t
imei
sdenot p(
edbyt i
nst
ancechar
act
eri
sti
cs)
.
Esti
mationoftpisdonebyknowingthechar
acteri
sti
csoft hecompilertobeused
andthenproceedi
ngtodetermi
nethenumberofaddit
ions,subt
ract
ions,
mul t
ipl
i
cat
ions,
di
visi
ons,compares,
loads,
stor
esandsoon,t
hatwouldbemadebyt hecodeforP.
Ther
efor
e,t
p(n)=caADD(
n)+cbSUB(
n)+cm MUL(
n)+cdDI
V(n)
wher
e ndenot
est
hei
nst
ancechar
act
eri
sti
cs
ca,cb,cm,cd denotetheti
mer
equi
redf
oranaddi
ti
on,subt
ract
ion,
multi
pli
cat
ion,
divisi
onetc.
ADD,SUB,MUL,DI Vet c.
,ar
efuncti
onswhosev aluei
sthenumberof
addi
t i
ons,subtr
act
ions,multi
pli
cat
ions,divi
sions,et
c.,thatwillbe
perf
ormed when t he code forP i s used as an instance wi
th
character
ist
icn.
Note:Obtai
ninganexactfor
mulaisanimpossibl
etasksi
ncet
heti
meneededforanaddi
ti
on,
subtr
acti
on,multi
pli
cati
on,di
vi
sion,et
c.,of
tendependsontheact
ualnumbersbei
ngused
fort
heabov eoperat
ions.
I
nst
eadofdet
ermi
ningt
heexactnumberofoper
ati
ons(
+,-
,*,
/..
..
..
)thatar
eneeded
tosolveapr obl
em instancewi t
hcharacter
isti
csgiv
enbyn,alltheoperationsarelumped
toget
herandacounti sobt ai
nedforthet otalnumberofoperat
ionsi.e,countonlythe
numberofpr ogram st eps.A progr
am st ep isloosel
y def
ined as a sy nt
act
ical
ly or
semantical
l
y meaningfulsegmentofa pr ogr
am thathas an execution ti
me thati s
i
ndependentoftheinstancecharact
eri
stics.
Thenumberofstepsofanypr ogr
am statementi
stobeassi
gneddependsont
he
nat
ureoft
hest
atement
.Thev ar
iousst
atementtypesare:
Comments–Non-execut
ablest
atementswhichhasast
epcountof0.
Declar
ati
vestat
ements–Def i
nesvar
iabl
esandconst
ants,owndat
aty
pes,access
specif
ier
sandfunct
iondef
ini
ti
ons,
whi
chhasastepcountof0.
Expressi
onsandassi
gnmentstatements–Mostexpr
essi
onshav
eastepcountof1,
exceptforexpr
essi
onsthatcontainfunct
ioncal
l
s,wher
ethecostofi
nvoki
ngthe
functi
onshastobedeter
mined.
It
erati
onst at
ements– Thisclassofst at
ementsincl
udesthef or
,whil
eanddo
stat
ement s wher
ethe step counts ar
e consi
dered f
orthe contr
olpar
ti.
e,t
he
expressi
onsandtheini
ti
ali
zat
ionstatements.
Switchstat
ement–Thi sstat
ementconsist
sofaheaderfol
l
owedbyoneormore
setsofcondit
ion–statementpai
rsandthestepcount
sar
econsi
der
edonl
yfort
he
control
stat
ementsi
.e,expr
essi
onandcondit
ions.
I
f.
.el
sest
atement–Thi
sconsi
stsoft
hreepar
tsi
e.,
i
f(<expr>)<st
atement
s1>’
;
Funct
ionst
atement
s–Thesecountas0st
eps.
Jumpst at
ement
s–Thesei ncl
udeconti
nue,br
eak,got
o,r
etur
nandretur
n<expr>.
Eachhasast epcountof1exceptforret
urn<expr
>wherethecostof<expr
>is
i
ncluded.
Thebest-
casestepcounti
sthemi
nimum numberofst
epst
hatcanbeexecut
edf
or
thegi
venparameter
s.
Thewor
st-
casest
epcounti
sthemaxi
mum numberofst
epst
hatcanbeexecut
edf
or
t
hegi
venpar
amet
ers.
Theaver
age-casestepcounti
stheav
eragenumberofst
epsexecut
edoni
nst
ances
wit
hthegiv
enpar ameter
s.
Exampl
e:-(
fi
rstcount=0)
foatsum(
l f
loat*a, ntn)
consti
{
foats=0;
l /
/count
++
for(
inti=0;i<n;i
++)
{ /
/count++
s+=a[i]; /
/count++
} /
/nt i
mes
ret
urns; /
/count++
}
Ther
efor
e,Ti
meT(
P)=1+2n+2=2n+3
1.
1.1.
3Bi
g-Onot
ati
on
(
1)Bi
g“Oh”not
ati
on
Def
ini
ti
on:f(n)=O(g(
n))[
readas“fofnisbi
gohofgofn”]i
ff[
ifandonl
yif]t
her
eexi
sts
posi
ti
veconstantscandn0suchthatf
(n)≤cg(
n)foral
ln,
n≥0.
[
Not
e:fandgar
enon-
negat
ivef
unct
ions]
Alt
hough1000ni slargerthann2f orsmallv aluesofn, n2growsatafasterrat
eandthus
2
n wil
leventual
lybethelargerfuncti
on.Thet urningpointisinthecaseofn=1000.
Thedefini
ti
onsay sthatev ent
uall
yt her
ei ssomepoi ntn0 pastwhi
chc.g(n)isal
waysat
l
eastaslargeasf (
n),sothatifconstantfactorsar eignored,g(n)i
satl
eastasbi gasf(
n).I
n
t
heabov ecase,wehav e
f(
n)=1000n, g′
(n)=n2,n0=1000&c=1[ canal sousen0=10&c=100]
Thus,
wecansayt n2)
hat1000n=O( .Thi
snot
ati
oni
sknownasBi
g-Ohnot
ati
on.
Exampl
es:
3n+2=O(
n)as3n+2≤4nf
oral
ln≥2
3n+3=O(
n)as3n+3≤4nf
oral
ln≥3
10n2+4n+2=O(n2)as10n2+4n+2≤11n2forn≥5
n 2 n n 2 n
6*2 +n =O(
2)as6*2 +n ≤7*2f orn≥4
O(
1)denot esacomput ingtimet
hati
saconst
ant
.
O(
n)i scall
edli
near.
n2)i
O( scalledquadrati
c.
3
O(
n)i scalledcubic.
2n)i
O( scalledexponential
.
O(
logn)i scall
edlogari
thmic.
Ifanal
gorit
hm t
akest
imeO(logn),i
tisfast
erf
orsuf
fi
cient
lylar
gen,t
hani
thadt
aken
2
O(
n).Si
mil
arl
y,O(nl
ogn)i
sbet
terthanO(
n)butnotasgoodasO( n).
(
2)“
Omega”not
ati
on
Defi
nit
ion:f
(n)=Ω(g(
n))i
fft
her
eexi
stposi
ti
veconst
ant
scandn0 sucht
hatf
(n)≥cg(
n)
f
oral
l
n≥n0.
(
3)“
Thet
a”not
ati
on
Defi
nit
ion:f(
n)=θ( g(
n))i
fft
her
eexi
stposi
ti
veconst
ant
sc1,
c2andn0 sucht
hatc1g(
n)≤
f(
n)≥c2g( n)foral
ln,n≥n0.
(
4)Smal
l“oh”not
ati
on
Def
ini
ti
on:f(
n)=o( g(
n))ifforallconst
antsc,thereexi
stsann0suchthatf
(n)<cg(n)
when
n>n0.Lessf ormall
y,f(n)=o(g(
n))i
ff(n)=O(g(n)
)andf
(n)=O(g(
n))andf
(n)
≠
θ(g(
n))
.
1.
1.2 Di
ff
erentt
ypesofdat
ast
ruct
ures–l
i
nearandnon-
li
near
Def i
niti
onofDat aSt ructure:Adat ast r
uctureisamet hodf ororganizi ngandst ori
ngdat a
whi chwouldal lowef fi
cientdatar etri
evalandusage.
Diff
erentki ndsofdat ast ructur
esar esuitedt odi f
ferentki ndsofappl i
cati
ons,and
somear ehighl yspeciali
zedt ospeci f
ictasks.Forexampl e,B-tr
eesar epar ti
cularl
ysui tedfor
i
mpl ementationofdat abases,whi l
ecompi l
erimplement ationsusual lyusehasht ablest o
l
ookupi dentifi
ers.
Datast ructuresar egener all
ybasedont heabi l
ityofacomput ert of etchandst ore
dataatanypl acei nitsmemor y,specifiedbyanaddr ess.Thus,t her ecor dandar raydat a
structuresarebasedoncomput ingtheaddr essesofdat ai temswi thar it
hmet icoper ati
ons;
whi l
et helinkeddat astructuresar ebasedonst ori
ngaddr essesofdat ai t
emswi thint he
structureit
self.Maydat astructuresusebot hpri
ncipl
es,somet i
mescombi ned.
Thei mpl ement ati
onofadat astructureusuall
yr equireswr iti
ngasetofpr ocedur es
thatcr eat
eandmani pulat
ei nstancesoft hatstr
ucture.Theef fi
ciencyofadat ast ructure
cannotbe anal yzed separatelyf rom those oper at
ions.Thi sobser v ation mot i
vat est he
theoret
icalconceptofanabst ractdataty
pe, adat
astruct
uret hatisdef i
nedindir
ectlybythe
operati
ons thatmay be per formed on i t,and the mat hemat i
calpr opert
ies oft hose
operati
ons( i
ncludingthei
randspaceandt imecost).Commondat astructur
esincludearray,
l
inkedlist,hasht abl
e,graph,heap,Tree( binaryt
ree,B-t
ree,red-blacktree,avai
lt r
ee,tri
e),
stackandqueue.
Dat astr
uct ur
esisbroadlydiv
idedintot woas:
Li neardatastr
ucture
Non- l
i
neardatastruct
ure
1.
1.3 Basi
cdat
ast
ruct
ureoper
ati
ons–i
nser
ti
on,
del
eti
on,
sear
chandt
rav
erse
Themai
noperat
ionsthatcanbeperfor
medont hedat
astruct
uresar
e:
i
.Inser
ti
on :-I
tmeansi nser
ti
ngav al
ueataspeci
fi
edpositi
onindat
ast
ruct
ure.
i
i
. Del
eti
on : -I
tmeansdel
eti
ngapar
ti
cul
arv
aluef
rom aspeci
fi
edposi
ti
oni
nadat
a
st
ruct
ure.
i
i
i.Sear
chi
ng:
-Itmeanssear
chi
ngapar
ti
cul
ardat
ainacr
eat
eddat
ast
ruct
ure.
i
v.Traver
sing:-Itmeansreadi
ngandpr
ocessi
ng(
visi
ti
ng)eachandev
eryel
ementofa
datastr
uctureatl
eastonce.
1.
1.4 Abst
ractDat
aTy
pes(
ADTs)andC++cl
asses
Exampl
e:Abst r
actdatatype:Nat
uralNumber:-Thiscontai
nsthecl
assdefini
ti
onofNat ur
al
number
.Itisassumedt hattheBooleantypehasalreadybeendefi
nedelsewhere.[Natur
al
Numberisanorderedsubrangeofinteger
sstart
ingat0andendingasthemaxi mum int
eger
(MAXI
NT)ont hecomput er
.]
assNat
cl uralNumber{
publ
ic:
Natural
NumberZero() ; //
retur
ns0
BooleanIsZer
o(); //
if*t
hisis0,r
eturnTRUE, ot
herwisereturnsFALSE
Natural
NumberAdd(Nat ur
alNumbery )
; /
/ret
ur nthe smallerof* t
his+yand
MAXINT.
BooleanEqual(Nat
uralNumbery );/ /
ret
urnTRUEi f*thi
s==y ;otherwiseret
urn
FALSE.
Natural
NumberSuccessor ()
;//
if*t
hisisMAXINTr etur
nMAXI NT; otherwi
ser et
urn
//
*thi
s+1.
Natural
NumberSubst actNat
( ur
alNumbery );/
/if*thi
s<yr et
urn0;ot herwiseret
urn
*t
his-
y.
};
Thi
sADTcontai
nst
hecl
assdefi
nit
ionofNat
ural
Number.Her
e,i
tusesC++classt
o
def
ineanADT.Her
e,someoper
ator
sinC++l i
keoperat
or<<,whenover
loadedf
oruser-
defi
nedADTsdonotexi stasmemberf unct
ionsofthecorrespondi
ngclass.Rat
herthese
operat
orsexi
stasordi
naryC++funct
ions.Thus,t
heseoperati
onsar edecl
aredout
sidethe
C++classdef
ini
ti
onoftheADTeventhoughtheyareact
ual
lypar toft
heADT.
1.
1.5 Useofi
ter
ator
s
Aniter
atori
sanobj ectt
hatisusedtotr
aver
seallt
heelementsofacontainercl
ass.
[Acont ai
nerclassisacl assthatrepr
esent
sadat astr
uct
uret hatcontai
nsorstoresa
numberofdat aobj
ects.Object
scanusuall
ybeaddedtoordeletedfrom acont
ainercl
ass.
Ex)Ar
ray].
Needforit
erat
ors:
Someoft heoperat
ionst
hathast
obeper
for
medonacont
ainercl
assCmayi
ncl
ude
1.Pr i
ntal
linteger
sinC.
2.Obt
ainmax,
min,
mean,
medi
anormodeofal
li
nteger
sinC.
3.Obt
aint
hesum,
product
,orsum ofsquar
esofi
nteger
sinCet
c.
Tosolv
ethesepr
oblems,i
tisr
equi
redt
otraver
seallel
ementsofthecont
ainercl
ass.So,
i
nor
dert
otrav
erseal
ltheel
ementsoft
hecont
ainercl
ass,i
ter
ator
sareused.
C++STL:Att hecoreoftheC++StandardTemplateLibr
ary,ther
earet
hethreefol
lowing
wel
l-
str
uctur
edcomponents.
1.Cont ai
ners–Theyareusedtomanagecollect
ionsofobject
sofacer
tai
nkind.There
aresever
aldi
ff
erentt
ypesofcont
ainer
sli
kedeque,li
st,v
ector,
mapet
.
2.Al
gori
thms – They acton cont
ainer
s.They pr
ovi
de the means to per
for
m
i
nit
ial
i
zati
on,
sor
ti
ng,sear
chi
ngandtr
ansfor
mingoft
hecont
entsofcont
ainer
s.
3.I
terat
ors–Theyareusedtostepthr
ought heelementsofcol
l
ect
ionsofobj
ect
s.
Thesecol
l
ect
ionsmaybecont
ainer
sorsubsetsofcont
ainer
s.
I
ter
ati
onisoftwotypes:
i
.I ndexbasedit
erat
ion
i
i
.It
erat
orbasedi
ter
ati
on
i
.Indexbasedi
ter
ati
on
Thi
sisthenormaltypeofiter
ati
onusedi nC-
styl
ecode.I
tisusedi
nthel
oops.
Example)
for(i=0; i!
=size;i
++){
//accesselementsofv [i
]
//anycodei ncl
udingconti
nue,br
eak,r
etur
n
}
Thi
sisonl
yusedforsequenti
alr
andom accesscont
ainer
s(v
ect
or,
arr
ay,
deque)
.Itdoes
notworkf
orli
st,
for
ward-
li
stortheassoci
ati
vecontai
ner
s.
i
i
.It
erat
orbasedi
ter
ati
on
Toknowt
his,
iti
snecessar
ytoknowaboutv
ect
orandi
ter
ator
s.
Vector:Iti
sacont ai
ner,si
milartoanar raywi t
hanexceptionthati
taut omaticallyhandles
i
tsownst oragerequir
ementsincasei tgrows.“ Vect
or”isatemplat
eclasst hatisaper fect
repl
acementf ort
hegoodol dC- st
ylearrays.Itall
owsthesamenat uralsyntaxt hatisused
withplai
narraysthatoff
ersaser i
esofser vicesthatfr
eetheC++pr ogrammerf rom taking
careoftheall
ocatedmemor yandhelpoper atingconsi
stent
lyonthecontainedobj ect
s.
I
ter
ator
s:Ani t
erat
orisanyobj ectthat,poi
nti
ngtosomeelementinarangeofel
ements
(suchasanarrayoracontainer).I
thast heabil
it
ytoi
ter
atethr
ought
heelement
softhat
r
angeusingasetofoper
ator
s( withatleastt
heincr
ement(
++))
.
Exampl
efori
ter
atorbasedi
ter
ati
on:
for(autoi
t=v begi
. n()
;it!=v.end();++it
){
//ift
hecurr
entindexisneeded:
autoi=std::di
stance(
v.begin();i
t)
;
//accessel
ementi s*i
t
//anycodeincl
udingcontinue,break,ret
urn
}
Adv
ant
age:
Iti
smor
egener
icandwor
ksf
oral
lcont
ainer
s.
Di
sadv
ant
age:
Itneedsext
rawor
ktogett
hei
ndexoft
hecur
rentel
ement
.
Thef
oll
owi
ngpr
ogr
am showsbot
hthei
ndexbasedi
ter
ati
onandi
ter
atorbasedi
ter
ati
on
#incl
ude<iostream>
#incl
ude<vector >
usingnamespacest d;
i
ntmai n()
{
//creat eav ectortost orei nt
vector<int>v ec;
inti;
//displayt heor i
ginalsizeofv ec
cout<<"v ectorsi ze="<<vec. si
ze()<<endl ;
for(i
=0; i<5; i
++)
{
v ec.push_ back(i);
}
//displayext endedsi zeofv ec
cout<<"ext endedv ectorsi ze="<<vec.size()
<<endl;
//access5v aluesfrom t hev ector
for(i=0; i<5; i++)
{
cout <<" val
ueofv ec[ "
<<i<<"]="<<vec[i
]<<endl
;
}
//useofi teratortoaccesst hev alues
vect
or <int>::i
teratorv=vec.begin();
cout<<"vfront="<<v ec.
fr
ont (
)<<endl;
whil
e(v!=vec.end( )
){
cout<<"valueofv ="<<*v<<endl;
cout<<"v="<<&v<<endl ;
v++;
}
r
etur
n0;
}
1.
1.6 Ar
rayasanADTwi
thpr
int
Arr
ay()oper
ati
on
Alt
houghanar rayisusual
lyimpl ementedasaconsecut iv
esetofmemor y
l
ocations,thi
sisnotalway st
hecase.Anar rayisconsideredasasetofpairs,<i
ndex,
val
ue>,sucht hateachi ndexthatisdef inedhasav alueassociat
edwi t
hi t
.In
mathemat i
calt erms,t hi
sis cal
led as a correspondence ora mappi ng.When
consi
der i
ngar rayasanADT,i mportancei sgiventot heoper at
ionsthatcanbe
perf
ormedonanar r
ay.Themainoperationsare:
i
) Cr
eat
inganewar
ray
i
i
) Ret
ri
evi
ngav
aluef
rom t
hear
ray
i
i
i) St
ori
ngav
aluei
ntot
hear
ray
i
v) Pr
int
ingt
hear
rayv
alues
Acl
assdef
ini
ti
onf
oranar
rayADTcanbewr
it
tenasf
oll
ows:
assGener
cl alAr
ray{
f
loatRet
ri
eve(i
ndex,i
);
/
/if(ii
sintheindexsetoft
hear
ray
)ret
urnt
hef
loatassoci
atedwi
thii
nthear
ray
;
el
se
//si
gnal
aner
ror
.
v
oidStore(i
ndexi,f
loatx)
;
/
/if(ii
si ntheindexsetofthearr
ay)del
eteanypai
roft
hef
orm <i
,y>pr
esenti
n
t
hearray
//andinsertthenewpair<i
,x>;
elsesi
gnalaner
ror
.
v
oidpri
ntAr
ray
();
/
/if(
arr
ayisnotempty
)pr
i hev
ntt alueofeachi
ndexi
ntheI
ndexSet
.
}
;//endofGeneral
Arr
ay
ADT1.
1:Abst
ractDat peGener
aTy alAr
ray
Const
r orGener
uct alAr
r (
ayintj
,RangeLi
stl
i
st,
floati
nit
Val
ue=def
aul
tVal
ue):
Thi
s
producesanewar
rayoftheappropr
iat
esi
zeandt
ype.Al
lthei
temsar
eini
ti
all
ysett
o
thefl
oati
ngpoi
ntv
ari ei
abl ni
tVal
ue.
Retr
ieve(i
ndex,i):I
tacceptsanindexandreturnstheval
ueassoci
atedwi
tht
heindex
i
ftheindexisv ali
doranerrorifthei
ndexisinval
id.
Stor
e(i
ndexi ,fl
oatx):Itacceptsanindexandav al
ueofty
pefloatandr
epl
acesthe
<i
ndex, ol
dvalue>pairwi
ththe<index,newval
ue>pair.
pri
ntAr
ray():Itpri
ntsthev al
uesinthearrayie.
,foreachval
idi
ndex(fr
om t
he
RangeLi
st)i
ntheIndexSet
,theval
ueoft ndex<i
hati ndex,val
ue>i
sdi
spl
ayed.
Theadvant
ageofthi
sADTdefi
nit
ioni
sthatitcl
ear
lypoi
ntsoutthefactt
hatt
hear
rayi
sa
moregener
alst
ruct
uret
hana“
consecut
ivesetofmemoryl
ocati
ons”.
Gener
alAr
rayi
smor
egener
alt
hant
heC++ar
rayasi
tismor
efl
exi
bleaboutt
he
composi
ti
onoft
hei
ndexset
.
Di
sadv
ant
agesofC++ar
ray:
a)TheC++ar
rayr
equi
rest
hei
ndexsett
obeasetofconsecut
ivei
nteger
sst
art
ingat0.
b)C++doesnotcheckanar
rayi
ndext
oensur
ethati
tbel
ongst
other
angef
orwhi
ch
t
hear
rayi
sdef
ined.
1.
2 Under
standi
ngSt
ackandi
tsoper
ati
ons
1.
2.1 St
ackandi
tsoper
ati
ons–PushandPop
Defi
nit
ionofSt
ack:Stacki
sal i
neardat
ast r
uctur
ewhichcont ai
nsanorderedcol
lect
ionof
homogeneousdat
aelementswheretheinsert
ionanddel
etionoperati
onstakepl
aceatone
endonl yi
.e,i
tusestheprinci
pleofLastI nFirstOut(LIFO).Examplesthatusest hi
s
phenomenon
i
) Shunt
ingoft
rai
nsi
nar
ail
yar
d
i
i
) Shi
pmenti
nacar
go
i
i
i) Or
dersuppl
yinar
est
aur
ant
Incaseofarrayandli
nkedlist
,inser
ti
onsanddel
eti
onscanbedoneatanyposi
ti
on,buti
n
stack,
itcanbedoneonlyatoneendi .
e,att
het
opofthest
ack.
Basi
coper
ati
onsi
nast
ack
Theinserti
onanddeleti
onoper ati
onsofst ackarespecial
l
yt er
medasPUSH and
POPr especti
vel
yandt heposit
ionoft hest ackwheretheseoperati
onsareper f
ormedis
knownasTOPoft hest
ack.PEEPoper ati
onisusedt oshowthetopmost(data)el
ementi
na
stackwit
houtdeleti
ngi
t.Anelementinast ackister
medasI TEM.Themaxi mum numberof
el
ement sthatastackcanaccommodat eist er
medasSI ZE.Thefoll
owingfigur
eshowsa
typi
calvi
ewofstackdatastr
ucture.
PUSH I
tem n POP
TOP
I
tem 2
I
tem 1
BOTTOM
1.
2.2 Ar
rayr
epr
esent
ati
onofst
acks
Ast
ackmayber
epr
esent
edi
nthememor
yinv
ari
ousway
s.Mai
nlyt
her
ear
etwoway
s:
(
1)Usi
ngone-
dimensi
onal
arr
ay
(
2)Usi
ngSi
ngl
yLi
nkedLi
st
Inthearrayrepresentati
onofstacks,fi
rst
ly,amemor yblockofsuffi
cientsizeisal
locat
edto
accommodat efullcapaci
tyofthestack.Then,st
arti
ngfrom thefi
rstl
ocationofthememor y
block,
itemsoft hest ackcanbestoredinsequentialf
ashion.Thefoll
owingf i
gureshowsthe
arrayr
epresentati
onofst ack.
u :
:
:
l
+i-1 I
TEM i TOP
:
:
l
+2 I
TEM 3
l
+1 I
TEM 2
l I
TEM 1 Bot
to
t
h
I
TEM idenot
est
hei i
tem i
nthest
ack
landudenotethei
ndexr
angeofar
rayi
nuse,usual
l
yval
uesoft
hesear
e0
andSI
ZE-1respect
ivel
y
TOPisthepoint
ertopointt
heposi
ti
onofar
rayupt
owhi
chi
tisf
il
ledwi
tht
he
i
temsofstack.
Wi
tht
hisr
epr
esent
ati
on,
thef
oll
owi
ngt
wost
atuscanbest
ated.
TOP<l
EMPTY:
TOP>= u
FULL:
1.
2.3 St
ackADTwi
thpush(
),pop(
),st
ackf
ull
()andst
ackempt
y()
template<classKeyType>
classStack
{
//objects:Afini
teorderedl
i
stwithzeroormoreel
ements.
publi
c:
Stack(intMaxStackSize=Defaul
tSi
ze);
//Createanempt ystackwhosemaxi mum si
zeisMaxSt
ackSi
ze
BooleanIsSt
ackFull
();
//ifnumberofel ementsi
nthest
acki
sequalt
othemaxi
mum si
zeoft
hest
ack,r
etur
n
TRUE( 1)
;
//other
wise,r
etur
nFALSE(0).
BooleanI
sStackEmpty
();
//ifnumberofelementsi
nthest
acki
s0,
ret
urnTRUE(
1)el
ser
etur
nFALSE(
0).
v
oidPush(constKeyType&item)
;
/
/ifI
sStackFul
l()
,thenStackFul
l
();
elsei ti
nser t
em i
ntot
het
opoft
hest
ack.
KeyTy pe*Pop();
//ifIsStackEmpty(),thenSt
ackEmpt
y()andr
etur
n0;el
ser
emov
eandr
etur
napoi
ntert
o
t
het op
//elementoft hestack.
KeyType*Peep();
/ fI
/i sStackEmpty()
,thenSt
ackEmpt
y()andr
etur
n0;el
ser
etur
nthet
opmostel
ementi
n
thest
ack.
}
;
ADT1.
2:Abst
ractDat peSt
aTy ack
Dat
amemberdecl
arat
ionsar
e:
pr
ivat
e:
inttop;
KeyTy pe*st
ack;
intMaxSize;
Theconst
ruct
ordef
ini
tonofSt
i acki
s:
templat assKey
e<cl Ty
pe>
Stack<KeyTy
pe>:
:St
ack(ntMaxSt
i ackSi
ze):MaxSi
ze(
MaxSt
ackSi
ze)
{
stack=newKey Ty
pe[MaxSi
ze]
;
top=-1;
}
Thememberf
unct
ionsI
sSt
ackFul
l
()andI
sSt
ackEmpt
y()ar
eimpl
ement
edasf
oll
ows:
t
emplate<classKeyType>
i
nlneBool
i eanStack<KeyType>:
I
:sSt
ackFul
l
()
{
i
f(t
op==MaxSi ze-
1)ret
urnTRUE;
el
seret
urnFALSE;
}
t
emplate<classKeyTy
pe>
i
nlneBool
i eanStack<Key
Type>:
I
:sSt
ackEmpt
y()
{
i
f(t
op==- 1)retur
nTRUE;
el
seret
urnFALSE;
}
ThePush,
PopandPeepoper
ati
onsuset
hesef
unct
ionsasshownbel
ow:
t
emplate<classKey Type>
v
oidStack<Key Type>::Push(constKey
Type&i
tem)
;
{
i
f(I
sStackFull
())StackFull
();
sest
el ack[++t
op]=i t
em;
}
templ at
e<classKeyType>
Key Type*Stack<KeyType>::Pop()
;
{
if(IsSt
ackEmpt y
()){StackEmpty();
ret
urn0;
}
item =stack[t
op--
];
return&it
em;
}
templ at
e<classKeyType>
Key Type*Stack<KeyType>::Peep();
{
if(IsSt
ackEmpt y
()){StackEmpt y
();r
etur
n0;
}
item =stack[t
op];
return&it
em;
}
Thev al
uer eturnedbyPopandPeepi softypeKey Type*
,ratherthanKey Typeor
KeyType&t ohandl et hecasewhent hestackisempty.I
nthiscase,0isret
urned.StackFull
()
andStackEmpt y()ar ef uncti
onsthatdependonapar ti
cul
arappli
cati
on.Oftenwhenast ack
becomesf ull
, heSt
t ackFull(
)functi
onwillsi
gnalt
hatmorestorageneedstobeal l
ocatedand
theprogram i srerun.St ackEmpty()isof t
enameani ngf
ulcondit
ioninthecont extoft he
appli
cati
onf orwhi cht hest ackisbeingused.
1.
2.4I
nfi
x,Pr
efi
xandPost
fi
xexpr
essi
ons
Anexpr
essi
oni
smadeupofoper
ands,oper
ator
sanddel
i
mit
ers.Thef
oll
owi
ng
expr
ession
X=A/B–C+D*E–A*C
hasf i
veoper ands:A,B,C,DandE.Thought heseareallone-l
etterv
ar iabl
es,oper andscan
beanyl egalvariablenameorconst antinourprogramminglanguage.I nanyexpr ession,t
he
valuesthatvariablestakemustbeconsi st
entwiththeoperat
ionsperformedont hem.These
operati
onsar edescr i
bedbyt heoper at
ors.Thebasicarit
hmet i
coper atorsarepl us,minus,
ti
mesanddi vide(+,-,*,/)
.Otherari
thmeticoperat
orsincl
udeunar ymi nusand%.Asecond
classistherelati
onal oper
ator
s:<.<=,>,>=.==and<>.
I
nordertoconvertsuchanexpr
essiontoi
nstr
ucti
onunder
standablebythecomput er
,
onehast ofir
stdet er
mi netheexactorderinwhichtheoperator
sar eev al
uated.Each
oper
atorisgivenapr i
orityandtheexpressi
oniseval
uatedusi
ngt heseprior
it
ies.I
nt his
eval
uati
on,astackcanbeusedt ost
orethedif
fer
entoper
ator
sandoper ands.
Theexpr
essi
onscanbewr
it
teni
nthr
eet
ypesofnot
ati
on:
Inf
ix,
Post
fi
xandPr
efi
x.
i
) Inf
ixnotati
on:Theconventi
onalmethodofwrit
inganexpr
essi
oniscal
l
edInfi
x.
ExampleforI
nfi
xnotati
on:A+B,C-D,E*F,G/ H
Here,t
henotati
onis<operand> <oper
ator
> <oper
and> i.
e,t
heoperat
ori
sbet
ween
t
heoperands.
i
i
) Post
fi
xnot
ati
on:
Thi
susest
heconv
ent
ionofwr
it
ingt
heoper
ator
saf
tert
heoper
ands.
ExampleofPost
fixnot
ati
on:AB+,CD-,EF*,GH/
Her
e,thenotat
i s<oper
oni and> <oper
and><oper
ator
>.Thi
sisal
soknownasr
ever
se
Pol
i
shnotati
on.
i
i
i) Pr
efi
xnot
ati
on:
Thi
susest
heconv
ent
ionofwr
it
ingt
heoper
ator
sbef
oret
heoper
ands.
ExampleofPref
ixnotat
ion:+AB,-CD,*EF,/GH
Here,t
henotati
onis<operator
><operand> <oper
and>.Thi
sisal
soknownasPol
i
sh
not
ati
on.
Not
e:Inallt
heabovenotat
ions,aunaryoper
atorpr
ecedesit
soperand.
Fort
heev
aluat
ionofanar
it
hmet
icexpr
essi
on,
thef
oll
owi
ngt
wost
epsar
efol
l
owed.
(
1)Conv
ertt
heconv
ent
ional
inf
ixt
oei
therpost
fi
xorpr
efi
xnot
ati
on.
(
2)Ev
aluat
ethepost
fi
xorpr
efi
xnot
ati
onsr
espect
ivel
y.
(
1)Conv
ersi
onofi
nfi
xto
(
i) Post
fi
x
St
ep1:
Assumet
hef
ull
ypar
ent
hesi
zedv
ersi
onoft
hei
nfi
xexpr
essi
on.
Step2:Movealloper
ator
ssot
hatt
heyr
epl
acet
hei
rcor
respondi
ngr
ightpar
t
ofparent
hesi
s.
St
ep3:
Remov
eal
lpar
ent
hesi
s.
Exampl
e:1.Af
ull
ypar
ent
hesi
zedexpr
essi
on(
(A+(
(B^
C)-
D))
*(E-
(A/
C))
)
2.((A+((B^C)–D))*(E-(A/C)))
3.ABC^
D-+EAC/
-*
(
ii
) Pr
efi
x
St
ep1:
Assumet
hef
ull
ypar
ent
hesi
zedv
ersi
onoft
hei
nfi
xexpr
essi
on.
Step2:Moveal
loper
ator
ssot
hatt
heyr
epl
acet
hei
rcor
respondi
ngl
eftpar
tof
parent
hesi
s.
St
ep3:
Remov
eal
lpar
ent
hesi
s
Exampl
e:1.Af
ull
ypar
ent
hesi
zedexpr
essi
on(
(A+(
(B^
C)-
D))
*(E-
(A/
C))
)
2.((A+((B^C)–D))*(E-(A/C)))
3.*
+A-
^BCD-
E/AC
(
2)Ev
aluat
e
Thisisthemainadvant
age.
Inevaluat
ioni
npostfi
xnotat
ion,scanni
ngf
rom l
eftt
ori
ghti
srequi
redexact
ly
once.[Thi
sispossi
bleusi
ngstack].
Adv
antageofpostf
ixorprefixoverinf
ix:
i) Needforparenthesisiseli
minated.
ii
) Pri
ori
tyofoperatorsiseli
minated.
i
i
i) Evaluat
ionpr
ocessi
smuchsi
mpl
ert
hanat
tempt
ingadi
rectev
aluat
ionf
rom i
nfi
x
notati
on.
1.
2.5I
nfi
xtoPost
fi
xconv
ersi
onusi
ngSt
ackADT
Gener
alAl
gor
it
hm f
orconv
ersi
onofi
nfi
xexpr
essi
ont
opost
fi
xexpr
essi
on
(
1)Appendasy
mbol
‘)’
att
heendofagi
veni
nfi
xexpr
essi
on.
(
2)I
nit
ial
i
set
hest
ackwi
th‘
(’
.
(
3)Readoneinputsymbolatati
meanddecidewhet
herithast
obepushedi
ntot
he
st
ack.Thi
sdeci
sionwil
lbegov
ernedbyt
hefol
l
owi
ngtabl
e.
I
n-st
ackpr
ior
it
yval
ue I
n-comi
ngpr
ior
it
yval
ue
Sy
mbol
I
SP I
CP
+- 2 1
*/ 4 3
^ 5 6
oper
and 8 7
( 0 9
) - 0
(
4)From t
het abl
e,twopr
ior
it
yval
uesar
edeci
dedi
.e,i
n-st
ackpr
ior
it
y(I
SP)andi
n-
comingpr
iori
ty(I
CP)
.
a.Asymbolwi
l
lbepushedint
othest
acki
fit
sICPv
aluei
sgr
eat
ert
hant
heI
SP
val
ueoft
hetopmostel
ement
.
i
.e,i
f(I
CP(
it
em)>I
SP(
x))t
henPUSH(
x)andPUSH(
it
em)
.
b.Simil
arl
y,asymbolwil
lbepoppedf
rom t
hestacki
fit
sISPv
aluei
sgr
eat
er
thanorequal
totheI
CPv al
ueoft
hei
ncomingel
ement
.
i
.e,i
f(I
SP(
x)>=I
CP(
it
em)
)thenPOP(
x).
Assumpt
ionsf
ort
heal
gor
it
hm:
Al
gor
it
hm I
NFI
X_TO_
POSTFI
X(E)
Input:E,si mple ari
thmet i
cexpressi
on ininfixnotat
ion del
i
mited atend bythe r
ight
parent
hesis‘ )
’,in-
comi ng and i
n-st
ack pri
orit
yv al
ues forallpossibl
e sy
mbolsin an
arit
hmeticexpressi
on.
Output:Anar i
thmeti
cexpr essi
oninpost
fi
xnot ati
on.
DataStructur
e:Ar r
ayr epr
esentat
ionofstackADTsaySt ackwithTOPast hepoi
ntert
ot he
top-mostelement.
Steps:
(
1)St
ack<char
>St
ack /
/Cr
eat
east
ackusi
ngst
ackADT
(
2)St
ack.
PUSH(
‘(
’) /
/Ini
ti
ali
zet
hest
ack
(
3)Whi
l
e(St
acknotempt
y)do
1.i
tem =E.
READ_
SYMBOL() /
/Scant
henextsy
mbol
ini
nfi
xexpr
essi
on
2.x=St
ack.
POP() /
/Gett
henexti
tem f
rom t
hest
ack
3.Case:
item =oper
and /
/Ift
hesy
mbol
isanoper
and
i
.St
ack.
PUSH(
x) /
/Thest
ackwi
l
lremai
nthesame
i
i
.OUTPUT(
it
em) /
/Addt
hesy
mbol
int
otheout
putexpr
essi
on
4.Case:
item =‘
)’ /
/Scanr
eachest
oit
send
i
.Whi
l
e(x≠‘
(’
)do
a)OUTPUT(
x)
b)x=St
ack.
POP(
)
i
i
.EndWhi
l
e
5.Case:
ISP(
x)>=I
CP(
it
em)
i
.Whi
l
e(I
SP(
x)>=I
CP(
it
em)
)do
a)OUTPUT(
x)
b)x=St
ack.
POP()
i
i
.EndWhi
l
e
i
i
i.St
ack.
PUSH(
x)
i
v.St
ack.
PUSH(
it
em)
6.Case:
ISP(
x)<I
CP(
it
em)
i
.St
ack.
PUSH(
x)
i
i
.St
ack.
PUSH(
it
em)
7.Ot
her
wise:
Pri
nt“
Inv
ali
dExpr
essi
on”
(
4)EndWhi
l
e
(
5)St
op
Exampl e:Letusver
if
ytheabov
epr
ocedur
eINFI
X_TO_
POSTFI
Xwi
tht
hef
oll
owi
ngar
it
hmet
ic
expression:
Input: (A+B)^C-(D * E ) / F )
Symbol readi
ng:12345678910111213141516
ReadSy
mbol St
ack Out
put
I
nit
ial (
1 (
(
2 (
( A
3 (
(+ A
4 (
(+ AB
5 ( AB+
6 (
^ AB+
7 (
^ AB+C
8 (
- AB+C^
9 (
-( AB+C^
10 (
-( AB+C^
D
11 (
-(
* AB+C^
D
12 (
-(
* AB+C^
DE
13 (
- AB+C^
DE*
14 (
-/ AB+C^
DE*
15 (
-/ AB+C^
DE*
F
16 AB+C^
DE*
F/-
1.
2.6 Eval
uat
ionofPost
fi
xexpr
essi
onusi
ngSt
ackADT
Foragiv
enexpressioninpostf
ixnot
ati
on,i
tcanbeeasi
lyev
aluated.Thef
oll
owi
ngal
gor
ithm
EVAL_POSTFI
Xist oevaluat
eanarit
hmeti
cexpressi
oni
npostfi
xnotati
onusi
ngast
ack.
Al
gor
it
hm :
EVAL_
POSTFI
X(E)
Input:E,anexpressi
oninpostfi
xnotat
ion,wi
tht
hevalueoftheoper
andsappeari
ngint
he
expressi
on.
Output: Val
ueoftheexpr
essi
on.
DataSt r
uctur
e:StackADTusingarr
aywithTOPasthepoint
ertot
hetop-
mostelement
.
St
eps:
(
1)st
ack<char
>St
ack /
/Cr
eat
east
ackusi
ngst
ackADT
(
2)Appendaspeci
alsy
mbol
‘#’
att
heendoft
heexpr
essi
on
(
3)I
tem =E.
READ_
SYMBOL() /
/Readt
hef
ir
stsy
mbol
from E(
post
fi
x)
(
4)Whi
l
e(i
tem ≠‘
#’)do
i
.If(
it
em =oper
and)t
hen
a) St
ack.
PUSH(
it
em) /
/Oper
andi
sfi
rstpushedi
ntot
hest
ack
i
i
. El
se
a) op=i
tem /
/it
em i
sanoper
ator
b) y=St
ack.
POP() /
/ri
ght
-mostoper
andofcur
rentoper
ator
c) x=St
ack.
POP() /
/lef
t-
mostoper
andofcur
rentoper
ator
d) t=xopy /
/perf
ormtheoper at
ionwithoper
ator‘
op’
and
/
/oper
andsxandy
e) St
ack.
PUSH(
t) /
/Pushtheresul
tintostack
i
i
i.EndI
f
i
v.I
tem =E.
READ_
SYMBOL() /
/Readt
henexti
tem f
rom E
(
5)EndWhi
l
e
(
6)v
alue=St
ack.
POP()
(
7)Ret
urn(
val
ue)
(
8)St
op
Exampl
e:
I
nfi
x : (
A+(
(B*C)/
D))
Post
fi
x:ABC*D/+
I
nput :ABC*D/+#withA=2,
B=3,
C=4andD=6
ReadSy
mbol St
ack
A 2 PUSH(
A=2)
B 23 PUSH(
B=3)
C 234 PUSH(
C=4)
* 212 POP(
4),
POP(
3),
PUSH(
T=12)
D 2126 PUSH(
D=6)
/ 22 POP(
6),
POP(
12)
,PUSH(
T=2)
+ 4 POP(
2),
POP(
2),
PUSH(
T=4)
# v
alue=POP()whi
chi
s4
1.
3 Under
standi
ngQueuesandi
tsoper
ati
ons
Defi
nit
ionofqueue:
Aqueuei sanor der
edcol
lecti
onofhomogeneousdataelement
swhereinsert
ionand
del
eti
onoper ati
onstakeplaceattwoextremeendsi.e,i
tusesthepri
nci
pleofFir
stInFir
st
Out(FI
FO) .I
tisal i
neardatast
ructur
eli
kearr
ay,st
ackandl i
nkedli
stwhereorder
ingofthe
el
ement sareinli
nearfashi
on.
Here,t
hequeueinser
ti
on(calledenqueue)oper
ati
ont akesplaceatthe“r
ear
”end
anddelet
ion( eddequeue)oper
cal
l ationtakespl he“
aceatt front”end.Thefol
lowi
ngfi
gur
e
repr
esent
samodel ofqueuestr
uct
ure.
r
ear f
ront
Enqueue • • •
•••
•••
••• • • Dequeue
Fi
g:Model
ofaQueue
3.Jobschedul
ing:Queuesarefr
equentl
yusedi
ncomputerprogrammingandat ypi
cal
exampl
eisthecreati
onofjobqueuebyanoperat
ingsyst
em.Iftheoperat
ingsyst
em
doesnotusepr ior
it
ies,t
hent hejobsarepr
ocessedintheor dertheyenterthe
syst
em.
1.
3.1 Queueandi
tsoper
ati
ons–I
nser
tandDel
ete
Ther
ear
etwoway
stor
epr
esentaqueuei
nmemor
y:
1.Usi
nganar
ray:
-Usedwher
eaqueueoff
ixedsi
zei
srequi
red.
2.Usi
ngLinkedList:
-Usesdoubl
yli
nkedl
i
standpr
ovi
desaqueuewhosesi
zecanv
ary
dur
ingprocessi
ng.
Repr
esent
ati
onofqueuesusi
ngar
ray
s
Aone-di
mensi
onalarray
,sayQ[0..
..
..n-
1]canbeusedt
orepr
esentaqueue.Thef
oll
owi
ng
f
igur
eshowsaninstanceofsuchaqueue.
3
2
1
n-
n-
n-
0 1 2 3
•• ••
f
ront r
ear
“f
ront”and“rear”ar
etwopoint
ers,usedtoi ndi
cat
et woendsofthequeue.Fori
nser
ti
on,
poi err
nt earwil
lbeconsi
der
edandfordelet
ion,poi
nterfr
ontwi
l
lbeconsi
dered.
Thr
eest
atesoft
hequeuehereare:
1.QueueisEmpty:f
ront=rear=-
1
2.Queuei
sFul
l
:rear=MaxSi
ze-
1
3.Queuecont
ainsel
ement>=0:
front<=r
ear
No.ofel
ement
s=r
ear–f
ront+1
TheQueueAbst
ractDat
aTy
pe
template<classKeyType>
classQueue
{
//objects:Afini
teor
deredli
stwi
thzeroormoreelement
s.
publi
c:
Queue( ntMaxQueueSi
i ze=Defaul
tSi
ze)
;
//Createanempt yqueuewhosemaximum sizeisMaxQueueSi
ze
BooleanIsQueueFul
l()
;
//ifnumberofel ementsi
nthequeuei
sequalt
othemaxi
mum si
zeoft
hequeue,r
etur
n
TRUE(1);
//other
wise,ret
urnFALSE(
0).
Bool
eanI
sQueueEmpty
();
//i
fnumberofel
ement
sinthequeuei
sequal
to0,
ret
urnTRUE(
1)el
ser
etur
nFALSE(
0).
v
oidEnqueue(
constKeyType&it
em);
/
/ifI
sQueueFul
l()
,thenQueueFul
l()
,el
sei ti
nser t
em atr
earoft
hequeue.
KeyType*Dequeue(
KeyType&);
//i
fIsQueueEmpty(),t
henQueueEmpt
y()andr
etur
n0;el
ser
emov
ethei
tem att
hef
ront
ofthe
//queueandr et
urnapoint
ertoit
.
};
ADT1.
3:Abst
ractDat peQueue
aTy
Ther epresent
ationofaqueuei nsequenti
allocati
onsismor ediffi
cultt
hant hatof
thestack.Thesi mplestschemeempl oysaone-dimensionalar
rayandt wov ari
ables,fr
ont
andrear.fr
ontisonel essthantheposit
ionofthefir
stelementinthequeue, andrearisthe
posi
ti
on oft helastelementi nthequeue.Thi sresultsinthef ol
lowing datamember
decl
arati
onsandconst r
uctordef
ini
tonofQueue:
i
pri
vate:
ntf
i ront
,rear
;
KeyType*Q;
ntMaxSi
i ze;
t
empl at assKey
e<cl Type>
Queue<KeyType>:Queue(
: ntMaxQueueSi
i ze):MaxSi
ze(
MaxQueueSi
ze)
{
Q=newKey Type[
MaxSize]
;
f
ront=rear=-1;
}
Thememberf
unct
ionsI
sQueueFul
l
()andI
sQueueEmpt
y()ar
eimpl
ement
edasf
oll
ows:
t
empl ate<classKeyType>
i
nlineBool eanQueue<KeyType>:
:IsQueueFul
l
()
{
i
f( r
ear==MaxSi ze-
1)r
eturnTRUE;
elsereturnFALSE;
}
t
empl ate<classKeyType>
i
nlineBool eanQueue<KeyType>:
:IsQueueEmpt
y()
{
i
f( f
ront=r ear=-
1)retur
nTRUE;
elsereturnFALSE;
}
Thememberf
unct
ionsenqueueanddequeuef
ori
nser
ti
onanddel
eti
onr
espect
ivel
yar
eas
fol
l
ows:
t
emplat
e<classKeyType>
v
oidQueue<KeyType>::Enqueue(
constKey
Type&i
tem)
/
/addi tem tothequeue
{
i
f(I
sQueueFul l
())QueueFul
l()
;
el
seif(I
sQueueEmpt y()){f
ront=0;
}
Q[++rear]=it
em;
}
templ ate<classKey Ty
pe>
Key Type*Queue<Key Type>:
:Dequeue()
//remov efrontelementfrom t
hequeue
{
i
f( I
sQueueEmpt y
()){QueueEmpty();
ret
urn0;
}
i
tem =Q[ front
];
f(f
i ront== r ear){rear=fr
ont=-1;}
elsef ront++;
returni t
em;
}
1.
3.2 Ci
rcul
arQueueandi
tsar
rayr
epr
esent
ati
on
Foraqueuer epresentedusingarr
ay,whenthe r
earpoi
nterr
eachesattheend,
i
nser
ti
onwillbedeniedev enifroom i
savai
l
abl hef
eatt r
ont.Thef
oll
owi
ngtabl
eshowsthi
s
ki
ndofworstcasethatcouldhappen.
f
ront r
ear CQ[
0] CQ[
1] CQ[
2] .
..
..
..
..
..
..
..
..
.. n-
[ 1] NextOper
ati
on
0 n-
1 J1 J2 J3 .
..
..
..
..
..
..
..
..
.. Jn i
nit
ial
stat
e
1 n-
1 J2 J3 .
..
..
..
..
..
..
..
..
.. Jn del
eteJ1
addJn+1( notadded
si
ncequeuei sful
l
1 n-
1 (
free) J2 J3 .
..
..
..
..
..
..
..
..
.. Jn eventhoughthereis
avai
labl
espaceatt he
fr
ont)
Onewayt oover
comet hi
sdi sadvantageofqueueistouseacir
culararray.Physical
ly,
acircul
ararrayi
sthesameasor dinaryarray,sayCQ[
0...
..
..n-
. 1],butl
ogicall
y,iti
mpl i
esthat
CQ[0]comesaf terCQ[
n-1]
.Thef oll
owingf igur
esshow physi
calandlogicalrepresentati
on
foracir
culararr
ay.
3
2
1
n-
n-
n-
0 1 2 3 j i
•• ••
f
ront r
ear
Fi
g:Ci
rcul
arar
ray(
Phy
sical
)
Fi
g:Ci
rcul
arqueue(
Logi
cal
)
Bothpoi
nter
s(frontandrear)wil
lmoveint hecl
ockwisedi
rect
ion.Thi
siscont
roll
ed
bythemod( %)f
uncti
on.Forexampl e,i
fthecurrentpoi
nterisati,t
henshifttothenext
l
ocati
onwi l
lbe(i+1)mod( MaxSize)where0≤i≤MaxSi ze–1(MaxSizeisqueuel
engthor
queuesize)
.Thus,fi
i =MaxSize–1, thenthenextposi
ti
onis0.
Twost
ates
1.Ci r
cul
arqueuei
semptymeansfr
ont=rear=-1
2.Ci r
cul
arqueuei
sful
lmeansfr
ont=(r
(ear+1)%MaxSi
ze)
1.
3.3 QueueADT( f
orci
rcul
arqueue)wi
thi
nser
t()/CEnqueue,
del
ete()/CDequeue,
QEmpty()andQFull
()
Amor eef f
ici
entqueuerepresentat
ionisobtai
nedbyr egardi
ngthearayCQ[
r MaxSize]as
circul
ar.Whenr ear=MaxSize–1,t henextelementisent edasCQ[
er 0]incasethatspotis
free.Thequeuewoul dbeempt yorf ul
lifitsati
sfi
est heabovement i
onedtwost at
es
respecti
v el
y.Ini
ti
all
y,wehavefront=rear=-1.Thefoll
owingADTshowst heCi
rcul
arQueue
ADTwhi chisthesameaQueueADTexceptf ordi
ffer
encesinthedef
ini
ti
onofthemember
functi
ons.
template<classKeyType>
classCQueue
{
//objects:
Af ini
teor
deredli
stwi
thzeroormor eelement
s.
publi
c:
CQueue(intMaxCQueueSize=Default
Size)
;
//Createanempt yqueuewhosemaxi mum sizeisMaxCQueueSi
ze
BooleanI
sCQueueFul
l()
;
//ifnumberofelementsi
nthequeuei
sequalt
othemaxi
mum si
zeoft
hequeue,r
etur
n
TRUE(1);
/
/ot
her
wise,
ret
urnFALSE(
0).
Bool
eanI
sCQueueEmpty
();
//i
fnumberofel
ement
sinthequeuei
sequal
to0,
ret
urnTRUE(
1)el
ser
etur
nFALSE(
0).
v
oidCEnqueue(
constKeyTy
pe&item)
;
/
/ifI
sCQueueFull
(),t
henCQueueFul
l
(),
elsei ti
nser t
em atr
earoft
hequeue.
Key
Type*CDequeue(KeyTy pe&)
;
//i
fIsCQueueEmpty
() ,thenCQueueEmpt
y()andr
etur
n0;el
ser
emov
ethei
tem att
he
f
rontofthe
//queueandretur
napoi ntertoi
t.
}
;
ADT1.
4:Abst
ractDat peCi
aTy rcul
arQueue
Thedat
amemberdecl
arat
ionsandconst
ruct
ordef
ini
tonofCi
i rcul
arQueuei
sasf
oll
ows:
pri
vate:
ntf
i ront
,rear
;
KeyType*CQ;
ntMaxSi
i ze;
templat assKey
e<cl Type>
CQueue<KeyType>:CQueue(
: intMaxCQueueSi
ze):MaxSi
ze(
MaxCQueueSi
ze)
{
CQ=newKey Type[
MaxSize];
fr
ont=rear=-1;
}
Thememberf
unct
ionsI
sCQueueFul
l
()andI
sCQueueEmpt
y()ar
eimpl
ement
edasf
oll
ows:
t
empl ate<classKeyType>
i
nlineBool eanCQueue<KeyTy
pe>::I
sCQueueFul
l
()
{
i
f( r
(ear+1)%MaxSi ze==f
ront
)retur
nTRUE;
elsereturnFALSE;
}
t
empl ate<classKeyType>
i
nlineBool eanCQueue<KeyTy
pe>:
:IsCQueueEmpt
y()
{
i
f( f
ront=r ear=-
1)retur
nTRUE;
elsereturnFALSE;
}
Thememberf
unct
ionsenqueueanddequeuef
ori
nser
ti
onanddel
eti
onr
espect
ivel
yar
eas
fol
l
ows:
t
empl
at assKey
e<cl Type>
v
oi dCQueue<Key Type>:
:CEnqueue(constKeyTy
pe&i
tem)
/
/addi t
em tothequeue
{
i
f( I
sCQueueFull ){CQueueFul
() l
();r
eturn;
}
elseif(I
sCQueueEmpty ){f
() ront=0; r
ear=0;}
ser
el ear=(rear+1)%MaxSi ze;
CQ[rear]=i
tem;
}
t
empl ate<classKey Type>
v
oi dCQueue<Key Type>::CDequeue()
/
/r emov efrontelementf r
om thequeue
{
i
f( I
sCQueueEmpt y()){CQueueEmpty()
;ret
urn0;
}
i
tem =CQ[ f
ront];
f(f
i ront== r ear){rear=front=-1;}
elsef ront=(front+1)%MaxSi ze;
returni t
em;
}
1.
3.4 Pr
ior
it
yQueueandDeque
1.
3.4.
1Pr
ior
it
yQueue
A pr
iori
tyqueuei sacol lecti
on ofel ementssuch t
hateach elementhasbeen
assi
gnedapr ior
ityandsucht hattheor deri
nwhi chelement
saredeletedandpr ocessed
comesfrom thefoll
owi
ngr ul
es.
1.Anelementofhi gherpri
ori
tyisprocessedbeforeanyel
ementofl
owerpr i
ori
ty.
2.Twoelementswit
ht hesamepr
ior
it
yar
epr
ocessedaccor
dingt
otheor
deri
nwhi
ch
theyar
eaddedtothequeue.
Apr ot
otypeofapr iori
tyqueueisatime-shari
ngsy st
em:programsofhi gherpri
orit
yare
processedfi
rst,andpr
ogr amswi t
hthesamepr ior
ityfor
m astandardqueue.
Inaprior
ityqueue,eachelementhasbeenassi gnedav al
ue, edpr
cal
l iori
tyoftheelement,
andanel ementcanbei nsert
edordeletednotonl yattheends,butatanyposi ti
onont he
queue.Thefollowingf
igureshowsapr i
orit
yqueue.
f
ront r
ear
A B • • • X • • • P
P1 P2 • • • Pi • • • Pn
Here,anel
ementXofpr ior
it
yPimaybedel etedbeforeandelementwhi chisatfr
ont.
Si
mil
arl
y,i
nsert
ionofanelementisbasedonitspriori
ty.I
nsteadofaddi ngi
taftert
herear,
it
maybeinser
tedataninter
mediateposi
ti
ondict
atedbyi tspri
ori
tyvalue.
Therearevar
iouswaysofimplement
ingthest r
uctureofapr i
orit
yqueue.Theseare
i
. Usi
ngasimple/cir
cul
ararr
ay
i
i
. Mul
ti-
queuer
epresent
ati
on
i
i
i.Usi
ngadoublyli
nkedl
ist
i
v.Usi
ngaheaptree
i
. Pr i
ori
tyqueueusi nganar ray
Inthi
srepr esentati
on,anar r
aycanbemai ntai
nedtohol dtheitem andi t
spri
ori
tyv al
ue.
Theelementwi l
lbei nsertedatt herearend.Thedel et
ionoper at
ionwillthenbeperformed
ei
therofthet wof ol
lowingway s:
a)St ar
tingf rom thef r
ontpoi nter,tr
aver
set hear r
ayf oranel ementoft hehi ghest
pri
ori
ty .Deletet hi
selementf rom thequeue.Ifthisisnott hef r
ont-mostelement,
shif
tal li
tstrail
ingelement saf tert
hedeletedelementonest rokeeacht ofi
llupt he
vacantposi t
ion.
X • • • • X • • • Y
• • • • • P • • • •
f
ront Del
eti
on r
ear
Shi
ftone
Thi
simplementati
onisver
yineff
ici
entasitinv
olv
essear
chi
ngthequeuefort
he
hi
ghestpr
ior
ityel
ementandshi
ft
ingthetr
ail
i
ngelement
saf
tert
hedel
eti
on.Abet
ter
i
mplementat
ionisasf
oll
ows:
Sor
taf
teri
nser
ti
on
X • • • • • • • • Y
Del
eti
on I
nser
ti
on
• • • • • • • • • •
f
ront r
ear
i
i
. Mul
ti
-queuer
epr
esent
ati
on
Thi
simpl
ement
ati
onassumesNdi
ff
erentpr
ior
it
yval
ues.Foreachpr
ior
it
yPi
,ther
ear
e
t
wopoi
nter
sFiandRicor
respondi
ngt
ofr
ontandr
earpoi
nter
srespect
ivel
y.Theel
ement
s
betweenFiandRiar
eal
lofequalpr
ior
it
yval
uePi
.Thef
oll
owi
ngf
igur
erepr
esent
sav
iewof
suchstr
uctur
e.
F1 R1 Fi Ri Fn Rn
••••••••••••••••••••••••••
Wi
tht
hisr
epr
esent
ati
on,anel
ementwi
thpr
ior
it
yval
uePiwi
l
lconsul
tFif
ordel
eti
onand
Rif
orinser
ti
on.Butt
hisi
mplementat
ionisassoci
atedwi
thnumberofdi
ff
icul
ti
es:
1.Itmayleadtohugeshi
ft
inginordert
omakear oom f
oranit
em t
obei nser
ted.
2.Lar
genumberofpoi
nter
sar
einv
olv
edwhent
her
angeofpr
ior
it
yval
uesar
elar
ge.
Ther
ear
etwoot
hert
echni
quest
orepr
esentmul
ti
-queuewhi
char
eshownbel
ow:
a)Mul
ti
plequeueswi
thsi
mpl
equeues
Her
e,foreachpri
ori
tyval
ue,asimplequeueistobemaint
ained.Anel
ementwi
l
lbe
addedi
ntoaparti
cul
arqueuedependi
ngoni
tspri
ori
tyv
alue.
Pr
ior
it
yP1 F R
• .
..
..
..
..
..
..
..
..
..
..
. •
Pr
ior
it
yP2 F R
• .
..
..
..
..
..
..
..
..
..
..
. •
Pr
ior
it
yPn F R
• .
..
..
..
..
..
..
..
..
..
..
. •
Adv
ant
age:
Mult
iqueuewi
thmul
ti
plequeuescanhav
edi
ff
erentqueuesofar
bit
rar
ylengt
h.
b)Mat
ri
xrepr
esent
ati
on
Thisi s bet
terthan the mult
ipl
e queue repr
esentat
ion.Her
e,we can getr
id of
f
mai
ntai
ningseveral
point
ersforf
rontandreari
nseveralqueues.
0 1 2 ••••• l
-1
1
• El
ement
shav
ingpr
ior
it
yval
ue
nx(
l-1)
Bot
htheserepr
esent
ati
onsarenoteconomi
cfr
om t
hememor
yut
il
izat
ionpoi
ntofv
iew;
maj
ori
tyoft
hememor yspacer
emai
nsvacant
.
1.
3.4.
2Deque
Anothervari
ati
onofthequeueist hedeque.Unli
kequeue,i
ndeque,bot
hinserti
on
anddelet
ionoperati
onscanbemadeatei therendofthestr
uctur
e.Actual
l
y,t
het
erm deque
i
sori
ginatedfrom doubl
eendedqueue.Suchast r
uct
ureisshownbelow.
f
ront r
ear
Del
eti
on Del
eti
on
I
nser
ti
on
·
··
··
··
··
··
··
·· I
nser
ti
on
From t
hedequest ructure,itisclearthatiti
sagener alrepresent
ationofbothstack
andqueue,orinotherwor ds,adequecanbeusedasast ackaswel lasaqueue.
Asimplemet hodtor epresentadequei susingadoubl yl i
nkedli
st.Anotherpopul
ar
repr
esentat
ionisusingaci rculararray.
Thefoll
owingf ouroper ati
onsar epossibleonadequewhi chconsi
stsalistofit
ems:
1. PUSHDQ( i
tem):Toi nsertit
em att hefrontendofthedeque.
2. POPDQ(): Tor emovet hefrontitem fr
om thedeque.
3. I
NJECT( i
tem):Toi nser tit
em att herearendofthedeque.
4. EJECT(): Tor emovet herearitem from thedeque.
Ty
pesofDeque
Ther
ear
etwov
ari
ati
onsi
fdeques:
1.I
nputr
est
ri
cteddeque
2.Out
putr
est
ri
cteddeque
1.I
nputr
est
ri
cteddeque:
I
tisadequewhi chall
owsi
nser
ti
onsatoneend(
sayr earend)onl
y,butal
l
ows
del
eti
onsatbot
hends.
f
ront rear
Del
eti
on
Del
eti
on ·
··
··
··
··
··
··
·· I
nser
ti
on
2.Out
putr
est
ri
cteddeque:
I
tisadequewheredel
eti
onst
akepl
aceatoneend(
sayf
rontend)onl
y,butal
l
ows
i
nsert
ionsatbot
hends.
f
ront r
ear
Del
eti
on
I
nser
ti
on
·
··
··
··
··
··
··
·· I
nser
ti
on