Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
66 views29 pages

Unit-2 DS Stack

1. A stack is a last-in, first-out data structure where new elements are added and removed from the same end, called the top. Elements are popped off the stack in the reverse order they were pushed on. 2. Basic stack operations include push, which adds an element to the top of the stack, and pop, which removes the topmost element. Other operations check if the stack is empty or full. 3. Stacks have many applications in computing, such as evaluating arithmetic expressions in postfix notation, checking balanced parentheses in expressions, and implementing the undo/redo functionality in programs.

Uploaded by

mcuthor98
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)
66 views29 pages

Unit-2 DS Stack

1. A stack is a last-in, first-out data structure where new elements are added and removed from the same end, called the top. Elements are popped off the stack in the reverse order they were pushed on. 2. Basic stack operations include push, which adds an element to the top of the stack, and pop, which removes the topmost element. Other operations check if the stack is empty or full. 3. Stacks have many applications in computing, such as evaluating arithmetic expressions in postfix notation, checking balanced parentheses in expressions, and implementing the undo/redo functionality in programs.

Uploaded by

mcuthor98
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/ 29

Stack 0

whot is Sack?
lat shuctune in which thne
Astack is a inons oata
o a new elemod and Jemoval an exRAn
elemed telces
elas olace at he Bame end eprenlos
the top ) the stack
To implemod tho sBack,it is negeined to maintaih
s he the
he potea to the top o the stac,lhich
lat elomod to bo ineed becae ce Can aces
elomods ony on dhe top o the stack.
LIFO (Leut in Krst out)
Baic aperations on Sdak fade.
elenen to the top d
e the
puh: Adds an elomend fram the stack.
Pop: (Romave, the topmas s empty:
Zmpty: chaes whdhe, the siaek
is whefhen the ghck ll.
üsFll chacds of he sdck.
topmasl elemend
top: Displays the
Puh stack.Tf the sdach is ll
Ades an idem to the
Said to be an corhtion.
Oventloj
then t is
Blasunm
baen stack Js fell
ifendiatn
elie
incremed top
erd Sck[top] ain vae
end ro Cacdng.
Pop:
INemoves an idem rom the sdack- The tems ane
Popped in the sawnsed onder in which they Scicl
puhed T{ the shack is empty ,fhen
be am Undetlow Conlitio.
to bo

if shack îis empy


endit
ele
Sdone voluo o stackStop]
decnmond top
JNetun vowe
emd ele
end procade
Top Ratns the top elemad e the stacd.
Algonihm
Sotun Stadh Ctop
end
empdy ele
fotse.
Ratus vue the Stack is
Alegonitna
i top)
Satnn true
e
netun ae
emdoca Bune
Rxed Si2e sdac k
As the name Sugget,a fod iz shock has a
Axed size cnd Camna! eiow oA shunk dy romy
the stadk is fell erd an ovnlow eror OCs
,an
add an elemod to
{ the sach is empty and an ttemy
S\emove am elomondrom it, m
Dynamic Size stack shwnk dynamicl
Can wen
Hdyremic Si2e stacke yno

Geveayavetiors stcles
Thoucu type
infie do Pasts stack iThis posc
inie espreiong to
Vsed to Conved
epeions. vostionStack; Thi tyee Sctck is
(R Exnmion 2 exprekions
wed do evlae postfix
sdack is ed to kep
This type omputn
(3 Recn ion Stech Colls ugiam an
in a
track of tuncdion tho coved fenction Lwhen a
to Jotn Contol to
Stck
the Praam Counte
is wel to stone tho voley
the ocyis kas in a Conpuln
ond th Values a to netuy o he
Preyiam,allowhg the proctem
previow, stale Cohon a finctron hetuns
c
S Balanad Panenlhovty Stack:Ths type o stach
uedo ched he balana f parendhwes in m
pon wedn
bUndo-Redo stck: Ty
This type t
o stadk s
ves to undo an
poorans to
Compe progans do alo
Sedo actions
inede estdoh stack inplemanttan wsng c
inlude stdibh
tmcdde Lstdboc\ -h
Il Nsll be the Copaity tho static Stack
*dohne N=looo
i| Trahalimg the top
ivt top~-y
H Lrhialnm the sdeck wmg an a

Noid ph;
jnd popl);
ivd pelkl0;

prntf("sTATTK ARRAv lrotal Capaaty: 2%\n, );


int choce:
whilel 2
printt ("mchooe any) the follomg
prny O: Exit 1: Push
3Peelkn" );
prny ("4: chad i the skeck itss empty
S. chack i the shack is fullln');
Scantl"oed", schoia)
Cane o: erid(o)
Cae 1: push(); brek;
Cane 2: pop(); brek,
Cau 3: pck() ; brealy
Cae A: isEnpty ); breaky
Cae s: isFull ), break,

3
3
Void puh()3
Tmplementdhom stack Linhed Lit
#indudo stdio.h>
#indudo < stlib.h
shuct node 3
int dot
struct nodenet
3;
Veid push (int vad) (si2edstrucd nade;
struct node hesNade=male
naNadedata= Val
nesNodo’nexthaad;
head nede
3
void popl)
shruct node *temp;
( head =zN)
stach is
3 Pntt"
el,
("Poped elemed =%1n head-gdsa);
prabg
temp=hand;
hoad =headnext;
Preeltemp);
3
VÛid pradList)
struct nooe temp hend;
lwhidel temp l= NUL)
pnintg (" ldl tompzdota;
temptemp next;

3
d main()
push (o);
pus h(20)
push(30),
prf"Lnead Lis\n"),
prntist);
Popl; is n;
prntf"Afa the pop,Hhe neJ ned
prntlisto;
pop(); new lnked n"):
prn"APtey the pep,the
prndist c);
natnn O;
3
Aoonhy: Bix to Postfix (a,p)
Suppose Qis an anishmalic eaprasion niten in
wntx notdton This ooenh Amd, ths agidant pastix
eapneion P.
lPush "e" onto sack and ad "y" Ao he end

tov each elemord a ntl tu stack is empty


3
4 T{ a dot prendis is encountoed puh it
onto sTACK
T an peto is encounJerad then:
()Rapegtedly pop from sTACK md add to
P each openoto (on the top sTACK)
which he dhoSme
prienity han .
(b) Add to shack.
[End IF souchwa )
6 T a iokd panerdheis is eniounteed thon:
a) Aapeatedly pop tram sIACK and ad to P
Coch opeatov lon tho top sback) Until o
Jat pavandhexis is encountaud.
b Remove the let penthais (Do nat add he
LEnd f shachwa
End o step2 Loap]
Covet . A+ (a*c-(o lEnF)*a)*H Jnto pastx
om shoo ha Soecr sotus.
at ho end epn
"y"
Now adod A+ (ac-(o/enpNa) H)
steck.
Cund aeo Push a c" On

Symbol Scamne Stack Expluciny


A
A
(+ A
(+ AB
AB
ABC
k.
(+( ABc*
(+(-C ABc D
(+-C ABc*D
Aec*DE
E
(+c-C1 ARC*DE
(+(-(In ABc*OEF
ABc*DEF^/
(+-@r
(+(-*
AsDEF^)a
As DEEn|G
(+ AB OBF^/ut
(+
(+* A8cDEfn|i
ABcDEF A/u-h4
)
evaaton da Poslfix Expreion
Suppose Pis cn ishmetic eopeion wen in
Posthx mootion.The FolloJM1 Which
SiAck to hold opernds, evotuates P.
Hleyonihm This alqonihm nds dhe VALWE 4 an
CUuthmaie epreion P wntten in pos e nototion
4 Ad a
[This acs ces asentndI.
2.Secn P fom de4 to ighd and seped step3
end t for ench elemd'of P ontl ths Sontind "y"
Às enCoent ered.
3 I{ en operamd is encowntd,pt it on STACK.
4 an openaton s entountal,then
(a) Remove the two top elemers ef stck,
whene A s Ihe top elemrd anl B is
tho neat-to-toe elemend

(c) Plece the seult éD f lb) bak on STACA


IErd o If stuctne
S Sel VAWE egt to the top elemet on SAh
6Exit.
Ariohmatie Exprotkiony. Polish Notatioa.
Lot o be cun authneie eopreujon involwmg
operatons Ths cecton oes
ape, an algonthm Lhich frds te value
sONeKe Polish (postfoc) notation.
The Jevel a precedenco -Lon the nl ve
binang operahons:
tihut: Exponentiatay (a)
Lowet: olitin ) aned subhaction (
Suppose we lwant to evauote thu
parentheistvee ouithmetie eprewjon :
bollong
243+*212-12/6
Fst espoNstrtien 231s24+ 126/
9+S *4 -12L
23
+20-2 231
Lout 229-2 26 2312
23s2
( 2312z14
A+(o4c- oert)*a)*h
A+ (oc*-(oEF1)a)*H
A+ (BetloEA)a-*H
A+ Bc* (oEF/H*
AB*/oEFN)Ht
Asc DEFA/ yt
Linled List implemoctian e sdacks
PUsHLLINksTACk (TNFD, LINK,ToP, AvAIL,ITEM)
This pnocalane puhes cn ITEm jto aLneed stack
1 LAVeualo spca?7 TE
AvAL=NUL, then Write
OVERFLoLJ ond Ezut.
R[Rome Grst nodo trom AvAL s
Set NEw= AUAIL end AVAL =NK [AVAILJ
S Sot INFo
CVE5l=TTEM rcopie Temnto new noeJ
4 Set LiNKSNeJ=ToP SNes node pont to
hu onignt
S.
top node in the stack]
Töp =NEW CRet Top to pant toho es node
at tho top d the stek

PDP_ LINKSTACK TTNFO, INk ,TOP, AAL, TTEM


Ths procedse dalade, the top elemad a dnked stack
and ais st to he anialle TTEM.
em no
IF ToP=NUL then Wnite
2 Set TEM =INFO CTOPT
UNDERFLOJ cnd Eit.
CCopies dhe top elemed a stack ino
3: Set TEMe =TOP cnd
ToP=LNK C+opT
LRemen tne dd volue of the ToP pnta ntEmP
cnd n t T0P to pot tothe next elomet nIhe
4 IRetun shack]
dolae node to tho AvAL lid
Set iNK [TEMA=AVAL cnd
S. Eoút. AVAL=TEme.
lRocunio

a Setond protedue 1hecd


conduning
erhen
Call tadomond do lsdf an a Call aoni,d do
may eventunlyJeNdt
n a Call sllomond back to he nignal pocecene
P. Then Pk Called c Necnive 2roceune
So had the prugtam will no conbue to n
nalmiely a Jecueve prosde moat have
-ths foleng Prqohies
() Thene mut be Coth cuteia
Caled be
Citeia, fox (hich he procaluue daes no coll
(R) Each'me the pocodus docs Call ird
sc
(drectg an ndnedly ), id mad be cloedo dhe
bae ceia:
A necnhve
2rocedene
Soid to bho elldh hod oih hee ppuhes is
Fachenmel mcdioy
() I no hen ml1
(b) Tf n>o then m!D(n)!
Fac doio (FA,N)
his Procalune caleal ades N! nd otns the voe
ün the Ncriablo FACT
I Y V=0,then FACT= | and fatunn.
2 Set FAT=| nitili 2e FACT for Loop
33 Roped foy k=l to N
Set FACT -KFACT
LEnd d Loop
Ratun.
FACTORIAL (FAT, N)
Thi pocadne Calalats N) an ety Jha vahein
he voui alolo FAT.
1: TNz0 then Set FACT=1 nd Retn
2Cal FACTo AIAL( FAT, N-1)
3 Sel FACT = NFACT
A Rotn.
Fbonacci Seqence
The colebratad ibonaci lequence lunally clenoted by
àlous:
S,&, 13, 2,34, S
O,l,, 2, 3, 5,8,
Demntn (Fbomaci Sequena)
(a) I! n=0 on n= hon n=h
(b) T then Fn=tn-tIn-)
Recunson (3)
FIBONAccT (FIB, N)
n the s
panamata FIB.
1 If N=0 on N=l then sefS FBN-N and Retu
Call FIB0NACCT(FIBA ,N-2).
3 Cal FIG0NAccT (Fl8B,N-)
A Sel FIß= FIBA + FBB.
S Retun.

Hekenmamn umchion
Tha Ackamann fncbion is a lunctin twth two
cugmsnto each LJhich can be asigned ng
monnagute -intay O,2--. This fac hin
follas
Ackamann tamcdion
(a) Im=o
T then Aom,n)-n+|.
(b) T m+o but n=o thon Am,n)A (m-i,1)
(c) 4 m+o ond n+o thon AGmyn)-A (m-1,A(m,h-)
Fnd A(U3)
Tail freun ion
a fenchion às caing tsoy and that secnsve
Call is he daut stalamend ina fenction then t
)S Called toil ecunsion. Aten thd cal thee
, t is no pefonng anyngso, is
undesng spleae haNe a lock ad he
Fov bate
boloo imae
funln)
in)
2 Ponjonmang Cone openotins
shatomod s the
funln-); Lout
foecunaVe Cal

Tal racwion.

you ned do Jomembe is, it The


So, the poind ShataAecunsve fndion Call then it
at atemand is thot
is Called taid lecnaon. This alo meo
al the openations will collingdne
ovyand the function Loill t bEveyhg pafomg
wetunhy time. :4
any operotion ad e Ihad is iy it
poryemad od colang
be cailod taid ouion. time ondy and
Eocumple
t* Jncludo estei.h>

Funln-i);
3
3
ind man)
funl3);
3
Nead tor Tail lRacusion
ne Coruicernd
The tei heCive
Dottertham nntaid
fnction
ácuve nchion
tel
Slacusin Cen be optmied by he Compiles
Compilo unaly escece ecve proceclue
wwing sdack. Th¯s steck cont ofal the pertnsnd
Anjomafon Cal.
;inedudeng dro panameta vaes, for ech
S\ecunve Wwhon a enocodneis caled, Ss
nyomaibn is puhed onto a shack. end lWhen
the funchion teimnate, the inyomatin i popee
out o tho stack. Thus or Ahe non-tailnemve
tunchons, he eck depth (maumum cmawrd
of stack space wsed ad amg tme duny Compilatiy
Recuwin to Itencion 0
int facton al (ind n)
natun
cie setn nfacderiel (n-),
3

iho Spae
hDy taid isnu the follany is implomentd
Jecnion, which Cen feduce the Si2e
e he funcdion'; ovenhsnd oy compla optimiztion.
int factani l int n, int )

Jetn ,
3 ele s

aloove Com be Jemoved bey


The ac ion mentionedCloop) cnd Stach.
-two oays 0 Tlenoton
o Reca sion flemovl
By Iferabion,The nules eplace the
OAecuion Cen be amaved by
d selocdion oith a doop.
Some dota noed to be vestonestep,afon pocmg
alte the end af the ecu dote
neded in adodon to the Loop
ktruetuna is
(3) The data soructne Veuy hrom a somple
to a stach
shing
înt farsonil (indn)

whileltvue)
if(n2) stnn ;
y=y*n;

3
3
By stack panamale,Vanjable labed)
Asdack fo each tho Jetun Value
R A vaiabo to ta neached,check
top stop Conditin is
3 17 Tho
whothen tho stack Js emptypop)ano jum to
the shack ~s not empy
4 Tf
ie appropiade abd.
empy,stun thoNenld
5 I{ thu stack is n)
S
Cind
ind tockanial
newa Stauk
stek P:
puch to sdack Po);
L2:
3 ese

Hkhack is ral emp)


Racuusion to eton (3
n= PopO;

3
notun;
3
Biny Seamch (ovide SCongen
Binay Seanch is dofned as a
Seanchng alganthm
Vsed Sna Santed
Sonted aaay
a by Thaepeatey Aivcong
idea o binany
he Secnchdeve in
Seanchs to wie tho nYomotioh het he
CUay is Soed andeduco the time
Complaity L2.3,
to o(loy N)
,3,678,4
Senh 23
826R38s6729
L-0 M=4 H=9
23 2
23>)6
82 16338 729)
M=7
2

8 l2|6 Q3)38S672)|
LFS H=6
Found R3
Seanch ina
Det ehuctue
Bhany Seoch algphm:
To apply syuctue mutbe Soted
’The data dod sorctue
’Accon to cuy elemsndeythe
tales Conukand ma.

Algerhn he Cemch sprce


mddl elemsdo
OCompre he eleraad, the
Lwtn the Key
fondat middle
key is
he Às teminatecl
8 Pnoceus eomt
at midalle
s nat folmd ued as the
O he kay thaly wil be
chase jhch
moxt seanch space dne midla
keyis smolle tham
9 I he hon the lot ide is vsed foy
elomond,
dham he mdle
(b) Sigd sids is sed
elemed,then the
londined until he lcey
(4) This, pracexs is Seanch Space s
s found anth total
eochousted.
Binany Beomh (s)
Ilenadin Malned Algonhm
do until the pointoas cnd high met ech
o'hon

I (x== cunCmid])
Setnmid
else it la>cn (nid) lxis on the Jifd idy
Jow= midt
high = mid-i
Racuwe Method
bneuySeandh (an, x, la high)
Sotn oale
ele
Eirad )
Sabun md
Cmid]) /riftside
sun 'ananuy Besmch (an,, midtl,
ele
nadun oeyoh(any,o,law,mid)
Bnony eanch
#jnlude stdio. h
antaycI,ind a,ind do,ind high)
ind bmcngSeanch(int
Lwile Clow e- high)
lowt high-las) /
ind mid

mid+ti
2 nigh= miel-t;
3
Setun;
înt man(Void)S
cney C3=3,4, ,6, , 8,93
ind

(amay ,o, n-);


ind Jentt binany Seooh
pruntf/"vo! found)
3

prantfl"samoudis foundt indac %4"


3 Yeutt)
Towen tlanoi
Tower od Honoi, às a mathematic puz2le lohich conish
thee towens (Cpegs) amcd moe than one nngs is
as depicted

A
and stackel
There únays diflarad
UPon in r asCending ´onden,i.e thesmale
othn ùatios
one. |hene are
One Sits oven fhe Janaen
1he pu22le whene the mumbe ff disks inceoe,
but the tower Ceoent Somh th same.
Rules move ol the disls to
)he ission is do
tower wihod violating dhe keqeence
Some ounathen folloawed for
7nmgmont. es ules to be
Tower of Hamo ani
one disk Com
Cem bemovel
be noved among
touwers ad any oven tme.
ony the "top disk cem be emove
Nolnge disk cen it over a small dick.

puzzle with i nisle Can
Towen o anoi proordtiy
be oved jn mininum n steps. this
shos hod punlo oth 3 disles has aleen
-l= 7teps.
Towen of Hanoi
lower Hanoi, is a mthematd puzzle lshich conistb
C thue towens loegs) amd mon tham ona
as depiched

difrd Si2e and stacke


Thae inog osden,i.e the smalle
UPon n an
One Sits oven
aconding
the Jarge one. Thene ane ohen Naiations
1he puz2le whens te numbe inrese,
distes
but tho towe Caolunt somany th sam
Rules move all the diss to
he mússion s to dhe Sequna
Sone omathen towen withod viodatngfollawed for
anamgement. Afew sude, to be
fTowen of Hanoi Cem bemoves amng sthe
onedisk
CUny gven time.
touwes moved
the "to disk cen be
’ ony smal disk.
disk Cem over a
’ No ange
puzzle wih radi ncisles Cam
Tower o tanoi This preerdat
bo ed in minimm n sdeps.
shos thad a puzndo ith 3disks hos talen
a-=7steps
Towen Hanoi (3)
Tawene Hano Can be
AJgonsthn
T wnite
Hrst we naed toanonn
algovtm ton Towen f ttenoi
how o sole this problem
Wih onen oumoun ol cisks, sey o 2. we mank
theeoues with neme, Socey clesnetion cml
aux (ony to help moviney the dicks). I we have ony
Ono disk hen t can eañy be move d Sonce
to dostination pee
If we hawe a isles - disk to auxey
move the smaller (top)
’ Fivst, we
’Then, we mave tho dnen(bottom) olisk to
7
dentination
And inaly
peg
ve
we move he smallen disk om
aux to dostnetion peg
So ow, we ane cinn aa postion to dlevign
toy Tower of HenoL. wth mon thantwo dis ks:
We divie'the stack o! disks in two ponts.
The anqed disk (nth elisk) is in one
olhenC ) icks ae in the Cecond peut
On wltmale aüm is to nove dish n trom Sonce
to dentinaton cnel then pd al othe Cns)aises onto
jt. we ceun imagne to applygel the Sane jn a
disks.
Secnsive way for all aven
The steps to follow
Step- Move n-1 disles hrom Sonce to aux.
Move nth isk tyom cona to det
step2- Move
Step3- Move -t disk trom aux to det.
Towen d lomoi (3)
H necun sve olsothm ov Towwen d Hnoi Can be
driwen s tollows--
START
Pnocedun tHovnoildisk, Sonc, det , auz)
T4 (disk==1) THEN
move disk from Qouuc to oot
Honoil clisk -l,Solce auk,
, elet) sdept
move disk fyom Sonce to det Istep
Hanoil disk-l,cux, clet,soune)
Endif
END Proledure
SToP

CProcrem tov tower od Hanoi


#include stio h
towen 0y Hanoi (ivd n, chan tomr,chan tod,
Void
chan auk Yod)

Cn=-)
pintf("n Move disk e from od %c to
sod oc", fromo,tasod ;
3
Hcenoi (n-, from roe, aux nod,tool);
toue,ol 7/
print("n Move disk Pocl Hrom sod bc to nod
n, Homnod,ted);
towerofHenoiln-,quxhod,t a ,hromrod)
3
int mainC)
Towen ef Hanoi (4)
I| Numhe disks
towe,oftamoi(n,A',d,e): | A, B amd C
umes o ocy

Tine Compleaty O(an)


Huikany Space: C)

You might also like