0% found this document useful (0 votes)
13 views25 pages

DS Module 2

Uploaded by

coyog64466
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views25 pages

DS Module 2

Uploaded by

coyog64466
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Stactebaueu

MODULE
ropresertation
Stacks' Definition, stacle openattond, odcpreorlohir9p
Stacl appabors - pol'sh
Staka, staclea wstng dyname aag
post ks prenson,
ocatorn, Tofix to postx Corvevstor, EValuabon oP
Kecurston, Factotal, GED, bonacei Seguenee, Towes Hanoi,
Ackerman's fanckon. Queuei Defpator. Aay vepreserntaBon
Queue operab'oro, ctrcular queues,n Circulas qeues
dynamde anag, dequeue, prlrithy gueues, A mag Problem
Mulkpk stac tes and queue, prcfam mng exaye
Tezt bookI ch 3:- 3b3.7
Textboolea: ch6: 6-1 b 6"3,6-5, 6-7, 6-8, b- 1o, 6"12. 6-13

The linear lsts ard lineor inser and olelete

elements at place in the s t - beg'ning. end,ddle.


One wants to vestict insesb'ons and olele bions take
lst, not the
place onty at the begn ng oY end of the
middle, a data stuctues stacl and queues

Stark:,Is a lneon olata strchu ve (an ordereo collectbn


iterno') in Wwch items may be aclolel oY Temoved oney
at one end. hast tem to be adoleg! to a stack s dhe Jrst
tn
ibem b be removed . hast in dst out (4IFo)
Other names h staclo - piles, Psholocwn l'stS
simudotng Tecurstorn is by means
mo

Stact operakiora'
elements are in seted oY deleted only at one end
calleo hp a dhe Btart.

Vaious operattor perbmeol on stact,

PUsh- wed to înset an element Pn a stacr

Pop - sed bo deloke Qn elemet


trom dhe 8tact.
>This tesm wed only h stack, not or odhey dota

Structure.
Overflow- check wbethex the stack s tell or not

undefow Checle whethe the stack ?s empy oY nol.

Posk poneel dec's or - gtacu ane seol to indlcate

bhe odes dhe


Requentl
olata when certain stees
of the proc mut be postPoned untt) other condhons are
esg
FuoBled.

A is the main B,c and D ane ubpngama


prugam.
callec Pn dhe ooder
8ven.
1he ele ment may be poppeol hiom de Stack
Onluy fn dhe reerse ovder eg that in Whteh they are puhed
Onty dhe Stack.
ay representak'on 2 sbeclst
AVAJA - Aist a valable hooles
- ee nodes were onty Rom he baginnng
removeo only
at be
new avallable nooles weve inserboo only

begnnrg 1P'st was implementeol Qs a Stack.

Staclu may be Yeprertedl by mea


last

top 0 oY top =NOLL (Stack s


Stack
empty
necy anay -stacle
3 S Potnbe vaviable - top
Variable - HAx
MA

Createl)
This Ph. tmplemenbed Stngle dimensona
SLSTAkS 2E];
Sgmbolie constant
arvay wsed b hold he elem ents
tbe stacl
dyned
STACS12E 5

int s[sTAcIN2);
Pash ( stach, bp .ma, ibem) n

pont oveflow ard reun


bop = Max dhen
a Set top:tbp+)
3" Set stack fbp] ibem

Pop ( staet,
top,tbem)
0 dhen pnt indefow and eun
bp
a Se Ptem
stack[top]
3" Set top
op-i

Hirindging underfbaw
ovev flo w

the
depend exçlsney and
|p data, tbere ho crct Contl Ehe
Pngammen
Overflow depend upon the abitrang Chofce of tho
Pnghammey yhe amgunt
Cach Stact, h chore oloes nfuere the
nenbey g bnes
overfbw mag OCC

Reseruing
(O) ceereae the each Stack
ho n bmes overflow
OCcur (expensive
8pace is seldon sed)
Reserving
incese he no"
a Small amount

Smes DVerflow orcu


9 spece hr each stacte

Tine reGured an overflow, Buch as


adding Space the Stacle , may be mnore expensve than Ehe
Space Saveol .

leehntque developeo' whch molA, bhe amay


epres entabon staclcs So that the emount 23pate reseveol

foy m0re than one stet mey be efBciently useol.

stack A with n, element


Stack r wih n element
If
Cuqo reG uire a staclko, overflow occuY ethe
Skacle A Contans more than n elemeot 0Y Stadt contauno

more than ng element.

instead, Single amay stak nan, tn, element


nh n-3

Operabo ns 2 Push anol Pop beed to be mooBed .


Stad [) bottom Stac A. to the ight

Stac [n) botbm stack B


Overflow wl Dccur when

have more than nn,+ ng elemens . cleereae the m


Ovevflow occurs even tho ugh not intYesel ho btal anoun t
b space reserveel foy hwo Staclus.
Ppplica ona 2staclk:
|.
Convevsfon
Prahemaheal expressbna wsng ink* presona.
Convest nb egu'valent mle nackoro by comple
Stacls
a. Evaluokon express'on
fhithrneke expreston eher the posthx Rrm
oY pre ka om s ea,ty evaluateo.
3 Recursor.

Af whth calls isel called recuxsve fn.


int kop:, Stakus =0;
Void push( int Stocx[J, int item)

PF(Shacle ovevfiow")
elbe

Stacie [++bp itemy


Statust+
3
3
int pop l int steckí))
int lemdel,

PfC "Stack underfow),


temdel =stuck[op --J;
Status--;
PFC" Popped element o, temdd);

ven tendel,

Votd dyglay (nt sta)

P"s tack emphy"),


elbe

P# (" Stac conlentS ne

o(iztop; i> z0;i--)


PP ("td, stach[ :);
Inan

opera

Staeh uotng dyname avap


gtake amao.
mastmun Size n dhe Stacle 8holcl be lknorendnt
OmpilaHon ore dhe size the stacr fs
Complabon, t s not possble b ale dhe siz ), Bhe Stacle
duning eyecukon
Overcome by dynam 0ay
To Stat let us
assume stacs is )
nt stackstzE =1,
dopt dyine stacsz£ a Constant
becaue Lsing aynamte may may
increase stacnsize ho
Oceommo dale more element So ik must be a Vaniable.
gname ama, Once tihe stack ts Pul, can
inerease the sizo y dhe amg exeeufon o inset nore

element.

Ex pressiona'
The
Seçuence 9 operahos and opeanol that
Yeduce to a
Stnge Value ofte ewaluakon.

Repverentakon Preky
PostRx
In an express?on, if an Openab is fn behween 2
operand. It Can be panenthestzed unpanendheszad
a+b

(atb)

Post&y:
In an expreson, iP dhe opeah Rilows a operondo
npanenthes.s expre»stor Also Caled Sufb 0 Yevevse pol:sh

PreRsIn an expreson, f an operato preced 2operando.


unparenthests expreson 91so Colleol poish esprensfon.
+ ab

opevh polsh no takon - The ovole in which the opeabos


are lo be pesmeol s
O, the opea
competaty
Gnd opeancl in he
delemhed
xpreason.
dhe posbons

ececlene n opebrs 0r prececeree Yules'


Rules that deternne the ovole tn wheh oerant
opeab1s ealuobed.
opeatovs have t,

precedence Tles
Tales ane
PrecedeNe dhen

asocitakvthy

The Oroles in which dhe operators cwt Bame

precedece ane evaluoted in an expreuston.

keft dght assocate lAelt


asocoFve):
more opeabc
xpresor 1f dher

hang dhe Same prionhy and are evaluated trom let b


Yight hen dhe called let assoe'aßve opeah.

0nle evaluabng post R or pre Rs espressfor, no necd


about precedene operahs and aasor iaRuhy g
Opeo where s wile evaluohng eprerson, lcnow dthe

precelere 9 ojpeaors and cwhether he operavs are lep


ght associabVe.

So Convest

1his is not stanoovd, Bome languages peshm ponenbabon


rom ight blegt.
(A+o) +C

3. (A+6) J(c-)
/+ Ae-cD

((A+(8-c) D)A E+ F)

(4e*-B DAE+F)
A+A - B(DE) +F)

++- A XAY2 MN/Pa


1. aab4c -dsel|(g)

Order
opeorda ore torne
orde y, operotos chomgs

presstrn'
Lot o be on ortthrnete esproston witer in igis
notakon.
hold opoas and byt
Parenthe»ts.

flgoithn' Inhu h pot k (0ip)


I’ puch onh stac and add ''to the
end a
Tepeat Step 3 to 6 By
each elament untl the stac ?s
emyh
3’1 an oPeand encountered oa od it bp
encoun tered. push it orto shac e
()
5 1 an opeah is entauntoed dhen
) Repeatodl pop Aam sta
opeaby (on dhe op Stect ) Which ha he me
hghe preceolere dhan oreahr
b) Add Dpeabr
opeahy b stack

6’ I a vqh
(endegi)
aventhes s erounteveol dhen
)a) Repea tnlly pop an Sach
Stack anod aod to pench
bhe top stack) un) a legt
opeatv(on
paventhe's s enentered
o Remove the let
parentheaisclo not aoed ahe legt parerdhaa)
(eno gstep2)

The posthx
expreson p on be
contctd rom
lege to sigt wstg dhe operonolo
trom aa and the peahus
are
removed Rom Stack
H
A+(B C- (D |E^F) #G)
Push ''onto stach and add'' bdhe enol 2 a.

Sumbel Sc anned Stacl

(+
(+(
(+(
(+(4
C (+(*
(+(
D
(+(
(+l-(
(+(-(!
(+(-/ ABrDE

(+(-(14 ABcDE

(+(-(19
(+l
(+(- 4
) (+(-*
(+
(+d
)
A+(B C- (D E^F) %G) H
A+ (6«c - (D | F ) c)* »

- (DEF 4I6 ) H

Iny bo postR:
I: ((A+ (&-c) D) ^ EF)

Y3^AM-N+po]+

abt c #de

aAbC - d+e|f| 9+%)


abac #d- eflah+ |+
and 6
Use a precedece fh f
F- Cotass the prerederce Values g 3gmbols on
Stack.
Contatns the prececdare valuo &ym bols in dhe
Shack
Symbols Ilp perederre
Prece ee
Assuc'avty
+, -
3 left

Yisht
óperan
left
(
lef
)

I a
opeab is left as oc ta Fve, stack prececere
Value is Ilp Preceolence Valve.
1 an
operah s ght assoctabve, &tacle preceoerce
Valu ts 2 |p Preceolene Vale.

Dutng COnvevsfon. orde


Opeabs change, berause
ea Openanls

Preceolence Vale the opeanola is


Same but the
preceolence Value 9 opehatos ne cfenont.
(A+(B-c) #D)
Stact
Stack s[bp) Symbo) F([hp]) >6(Bymbo) PostBx

#
( Push ( -179

Pop A 8 > |
( Pusht O)
# (+ ( Push ( 2>9

#(+( B
t (+(8 Pop B 87|
# (+( (

(+( Push c 7

C ) Pop c 8>0 Agc


) Pop - a70 Goc
t (+( ( )
(dont place in post kx)
push * a3
Push D
t(+*D ) Pop D 870
) Pop
Asc-D
A(+ +
Pop+
Pop 6
>0
(dont ptoa tn post ha)
I the ston ned choractey is Gn opead. push 't Cn tn
Stact.
If dhe sCanned character is on peahi (, peond,
openah, ard opeand, )
’ (a-(bl(c+ (dre)))
abc ’ ((a+b)- c)

Pre By ho igs
Revevse the prekx exprerson
IP dhe Scanned chaYacker s cn ope-ond pesh i on
b dhe stacr.
I dhe scannec characte s an opeabr, deverse he
Operand l, Sopeand, dpeabr, o ope.and , ).
) -alb #c^de
’ (a-(b (cu (dae)))
a) -+ cbc
’ (( a+b) -c)

Post &y b pre h


If dhe Stanneo characta 's an Opeant sh On
ho dhe stacle
If dhe Scanneol chavacte s an opab take
operandh om stark pe Rx the opeah.
) ab+c * de- - f+ A ’A - 4 4 abc- de* t9

rek to postls
Revevse dhe prek epresorn
oprand, push tt ono he
IP dhe Scannel characte is an

Stack.
I dhe Scanned choracte s an

Yevese ?t corcotenate with operathy

’abcde A /
) - alb + cAde
a) -+abc ’ab+¢ -

lo evaluate an nthmeke expreson wtten în yx notahon

’ Convet dhe expreAsfon to Postx notabon


valuctes dhe post k epres sfon.

The shack Ps dhe main tool b acconmplish dhe above

EValuokon ) expreston!
Operabs with highet preceslenee au evalateo rst
Expresfos ane always evaluateot hom dhe
innemes parendhesis exprexion t
postkx expres fon
Evaluakon 4posth
Consider P is an
aithmete exprer fon.
| ’ Ado a
vght panendheis) at the enod P(acts as a
Senkral)
SCan P Jnom left b ight and repeat step3 and
each element for
Pntounter.

encountered, Put it on Stack


encouotered dhen
a) Remove dhe op hwo
eleent
the op element and B s
Stact, wher A s
the neyt b op
b) Evaluote B A
element
c) place the resull back h stack

(end g step a)
S’ Set Valu esual h the bp elernet on Stack

To
Smpy dhe task, assume expreston contains
y opeats t,-,*, l, 7: ad
that dhe opeanolo in he
eApreson ae
when opeand s pusheol on to dhe stack, ts
Asc Valus wN1 be
pushe
Stnce an
Opeand(
andl synbo') s initally aa charcter
Want b push the cor esponolg integ value achienes
subt>gmbol
racng - 'o' 'o (48 olectmas)
olectmas ) srom
trom an opeond

The aboVe statement tajes dhe AStn Vale ymtol and

Bubhact he Aselp Vale y 'o

lample,
Symb'
Chararte ' has an AsÇ!
The statement Symol - 'o' Proouce
umbe
)
6a13- hatt
Symbol A stacl

6 6
6 a
6 3
3
W
3 3
3 3-3

) 8

Answe s 8

82| 3 - ha ( Inval
preston)
Recur

Re
3)
Aec

Answe = 31

A) EVoluate the pastRx expreastorn

A-b, B-3, C=&, D=S, E=l, F=1


63a-5 + I7+
Result )8
S) Evaluote the post kx expreston

6) Evauate the valid past expresion


A=1, B=2, C= 3
la+ 3 al+3

Reult -24
)

Relt
Recurston
Recuvsve Procedure - p is a preceoure conto'ning e'th er Q
Call Btaement to itse call &latemeot to a Becond
Proredlure that eveatualy a call satement
result
back toD the on'ginal Procedue p. ps called a ree ussAue
Procedure. So that the progham Col not contonue to vun

indnibely
Prapnte,
J" Thee must be cer kain criteva Caled bese cteria,
Poy whth the proceclue oloe not cal iksel.
d Each Bime the pcelure does cal sey (oety
indvetiy), it must be clese dhe base cster'a.
Recursve funckon
A fo s Sard b be

a prope es,
J" Thee must be cestain
argment calle d bcae valles Ror
which the on does not refe to itse.
a. £ach kme the tn doe refen to itse,, the
O, Ebe t mwt be
argeument
close to a base Value.
FORTRAN, COBOL oloes nok
Yecurs on.
The prooluet of the poskve integers trom lton.n
h! -|3... (n-a)(n-)n

n!=n(n-)!
n0 nl)
4n0. n!:n(n-))
The fode Boed br all non
regake integen

levet
3 32)

leve

3! =3a= b
level q

n=0 dhen Set soc t=t and rehin


a set tactst
3 Repeat or
oitai tochvad (Jort n)

cal fachal ( ect,n)


3: set Jort :n act

The depth g
Oghs exeruton a pocedueps astqned leve|.
Verurstorn a Yerusive pocelure P wth a gn Bet 2 sumeni
b dhe may. evel nmbo p duvng :t execuHr.

fbonace Sequene'
D,, ), a,3,5,8, )3,2,3h. 55,..

Foo
beo s dhe um g dhe kwo jpececg tem
Each Bucredg
if n> then Fn= Fn-gtFn

igaithn benacei ( fb.n)


nz0 oY n:) dhen Set b=n and ehn
2 call
3. Call
Ybonace'( b), n-a)

6 retun

You might also like