You are on page 1of 5

I .I.1 Crwll.. I S11ck .

Tht bullt•m d.il.1 s1n1cture list .iva1lable . t creates an addre


In Python. whtn you dt"clare/create a list, t der ro create 311 emP
numbt-r of htttrogrm•ous elements. Thus. in o~ven below:
. le and easy to implement Stack.
In Python makes it fleXI:, In memory and ca n ho ld any
ty Stack we just need to use
.
r Algorithm to display tap element With t d
1 START

2. St_len = le n(Stack)
3. ,f St_len == [I:
pr int("U nderfl ow"J
ou e 1etln& II, l.e~ peek()

#Count the total number of elements m a S13ck

1nbu1lt luncuon listl) or n as per the syntax g go to step 5


S)'ntax: 4_ Top = St_len-1
•an empty stack, 11st
Stac:t. • .. 1st() print(Top)
OR
s· \ _· ~- " l l tan empty stac
k, 11st I () f . 5. END
d Is created usmg 1st unction while
' .· hie ofllst type on ty pair of square brackets Algor ithm to check If Stack Is empty
Here. m the firs t line of code, Stack is a vai_ia ated by assigning an emp .
in th~ second line of code, Stack variable is ere . . I es are used. Thus, the first element 1. START
Like hsts. In order to access the elements in J t::
S k ,ndex va u r d
Stack[1J and so on. Unlike ists, ran om access 2. SUen = len(Stack)
,n the Stack will be Stack(OI, the second will be S k 3. if St_len == I] :
is not allowed for the ob1ects contained in the tac . prlnt("Underflow")
4. END
5.3.2 PUSH Operation/Adding Elements Into I Slack d PUSH operation. In Python, the list
St ck hst ,s calle .
Adding/Inserting a new element to th e a S k The syntax 1s: 5.3.4 Pop Operation/Deleting an Element from a Stack
function append(} Is used to add elements into the tac .
In Pyth on, the liSt function pop() is used to pop/remove/delete elements from a Stack. The
Synlllx: Stack . append (x I . and inserted at the end of the list implemented syntax 1s:
15
Here x 1s the element to be inserted into the Stack . fi st element to the Stack. Stack . pop ( I
' . ly appends thJS "
as a Stack. If Stack is an empty hst. it s,mp . T -n-l) where n is the size of the
st
Note: Attempts to insert an element into a rull ack, ,.e., ( op- ' Here,
Stack, 1s called Stack Overnow. • The function pop() removes the last element which is on the top of the Stack.
• It also returns the popped/deleted elements from the list .
Algorithm for PUSH Operation . Stack are as follows :
PUSH operation on t11e Therefore, in o rd er to delete an element from the Stack, no subscript/index value is required to
The steps to be performed for carrying out t he
be passed to th e function pop(). If a user tries to delete an element from the empty Stack, It IS
I. START called underflow of Stack.
.. . Stack using list
2. Stack=list(l or Stack=n #lnit,a 1,ze a k "
sta Algorithm to delete an element from a Stack
3. element = mput("Enter the value to be added m the c : l.
#Adding element into hst Steps to be followed are:
4. Stack.append(element)
5· ENO 1. START
. . ush the 'element' onto the Stack using
While we perform PUSH operation mto the Stack, we P 2. St_len = len(Stack) #Count the total number of elements ,n the Stack
append{) function. #Checks whether the Stack 1s empty or not
3. if St_len == []: or if not Stack: or ,f not len(Stack):
5.3.3 Checking the Status of Stack print("Stack is empty")
th
To use Stack efficiently, we need to check the status of Stack as well. For th e same purpose, e go to step 6
following functionality is added to Stack:
4. element= Stack.pop() #Removing last element from top of the Stack
(i) peek(l-To get the mos t recent value of stack, ,.e., top element of the Stack without removing
5. print(element)
Jt or value at the top. It will throw an exception if the Stack is empty or null.
6. END
(ii) Overnow-To check if Stack is full which leads to overflow while trying to insert a new
element in the Stack. In Python (for stack and queue implemented as list), since list ca n ► In the above algorithm, the 1/ cond1t1on shall check whether the Stack is empty or not.
grow, no overflow condition will arise until all memory is exhausted. In case of non-empty Stack only, the element shall be removed from the Stack using the
(Iii) Underflow- To check if Stack is empty which leads to underflow while trying to delete an built-in function pop() that removes last element.
element from the empty Stack. ► Once a n element is popped, the Stack automatically reduces one index pos1tton
practical lmplementat1on-2
El,_111 es as a collection of elements Write a program to display unique vowels
LI I 1Nftnlllt,'llllflQl11 Slack d ta cype that ser, ollectlon. and pop(), which
• Stack Is a a no the c h k th Present In lhe given word using Stack.
..., now M haw undorstood that a lch adds an elemen ved. In order to c ec e status
Wl
y'1h two principal operations: push(), wh h I was not yet remo performed, traversal of Stack ~p~~
tQa.lno,st..c,
0

the most ~cently • dde d element t ad POP operat1·ons arer m the top posi't'10n, 1.e.,
8 ' l t r ~ . . _ ~ ..
. Ias1
nmows k henever PUSH an elements ro =l~ ;~;•1:~:~:·~•,.-..,·1
or ~l•mrnts on lhe Stac w I traversal process, the se order. &tact• II ""'""'•-cit ..,.,~,, ..._u •
t-lemc.-nt> be-comes mandatory. n d rocessed in the rever r:, lnter l11,.,uc1
•flattar111 ._i..
1
lnsertrd elemen~ gel displayed an p 1

Alprlthm lor traversing Stack Elements:


f;lhtlt:.:::~.:.!:f~~l
prhltrlt,. ~ 1 014111.,.,u ••••'1111 p,._1 •••••ra.·u•,1ai:1n.cw,1
I START
z. I = len(Stack)
3. for I in range(l-1,-l,-l):
prlnt(Stackll])
4. End Explanation:

lementatlon-1 Stack, such as adding element In the above program, we have to find the number of non-repetitive vowels present in the inputted
Practical Imp I nt all basic operations of ad. laying the Stack elements word. This is done by comparing each letter of the word with the vowels lost and, when found. the
Wrote a Python program to Imp eme (POP operation) and ,sp
(PUSH operation). removing element vowels are added to the Stack (only unique vowels). Thus, Stack m the above program acts as a
(Traversal operation) using lists. container to hold all the vowels which are present m the given word and finally displayed using

.... - ... -- len(Stack) function with print() statement and, hence, the given output is obtained.

tl111Pl --t..tio11 o r l.llt u


Practical lmplementation-3
1t.c:t
••II
c-·r· Write a program to create a Stack called Employee, to perform the basic operations on Stack
..tlllo lc-' r"' I•
ptillt 1· 1 91QP•1
prltit t •J, POI "I using list. The list contains the two values-employee number and employee name. The program
:~!~.!:!l t~~;!!~!;~tu ,..,_, CNlce: "II should include the options for addition, deletion and display of employee detalis .
It ~!~~~!~t, - •"IY 11_,.,
1

•. ,ppend(f)
•l it tdlolw-llt
1 •1
.... - . . a.--... -
I Uoqtuo to idd, <klU• ind ClUphy tllll 1eco1a.. ot Ill DISJI~ ~• l r.q l ht
,ac,1-nutlonthrouqnst.ac\ ..... ____ _ I

H ':;;!!':, n"; ~ty• I tlllflOY""'ll


~~;~: 1e- •y•1,
print 1•1. l'IISll"I
>;;STU"t, C1\0H..\1><-.ll"'"'°"U\1.0c.tlVrOQ•-\JJ\ll""I
r::.:l-12\p<OQ.ll. . .PJ
print t"l , POP"I
prl11t 1•1. DUpl•Y"J
cbolc:e• lnttlhputt"lllt., y,x,r ebol:•: 1 .lllt pl•J
1t Cdlolo:w.-11 1 lf>U r:,,>1<c u,c,1ca , I
l!IIH llllpl...,.. ... I\
• ld• lnputl"l'.ntu laplO"f"M; ,.,
• ~• hput!"lntu t,.,_ a.pl~~•.._:')
""P • Ct_ld, e..,,..J
laplOYft . lppend(ap)
r:-~l
cau,u,._1ol'"..._
toDllflli»l,Or ,_,IJ
.,1at11
f

ell tldlolc-Jl: ). OU pLIJ


It t bipl oy,te-()11 a i .r,_.CIIOlc.1 \
llH~rlnt ("St.lie\ ltllipcy"J lllll1 C -l 117M ot01 t
...lUUll ~ l o y - . - OMl"'ll
e_ld, •MN"'laployee . pop(I lll>JOII U H to - t i - or _ , '

,1u
prlnt l"O.l Ued •l-11t u
tcboto.-11,
•, e _td, _ ) ~::!"
J.Ol.apl•J
l•lu!lllployN)

::~:: : 1: 0;:. !- r.a!W


a,u ,-,ou.rCN>lce , l

' ,o.i ,.,11t lltlll• I> O: no <11:rp11-y


prlntut,..loY" l1-lJI
,1-11u tr.. 11-,t 1 1 - t to tun
!., to coatl1111e or DOU Y 1 - 1-1 r 5 -"'UllOC.IU0.. H•II I
1. ,usa
J.,OP IIHI 11 J. lllopl-lt
prl11t1·wror,q, l put·1 lnl., ,-ic'">lce, 1
c-l11p11tl~DO ~ .,,nt tc Q<l~tl- ~r nou •1
~t:~•~~ cbOl«t L- ----------------71•2•, i• t •, •uun .1 •1

:1;;:4,.:!:-::t~t;no!1or110t1y
l

1.MII
J.,OP
}. Dhpl•Y
f 'll>l"'J" 'I

E~!~~~~ -ti~• 01 .OU I

CftUr your ebole-: J J.DitphJ

:
1
;:1,.:!~:\!:t~ni!'or IIOt? y :~:~.r:~~~~~:
Qoyou -
: I O AlLI
l toCOO.I UII.O•O• "'"ll J
I.fl/SIi
J.,or
l, Dllphy
~: :::!'
111t1ryoureholc:11: J ~t~~-~Cl\l>ICII )
C'2', 'ob.o»ry• ' 1
'~ you Wint to cont111u. or i:io:t1 11
_n ,~\~•~~:! - tu... o, _ , I


Appllcattons of Stacks
Some of the important applications of Stacks include: f . I'
f k pplication is reversa1o a given ine. This
1. Reversing a Word/Line: Asimple example O Slac • a Stack as it is read. When the line
can be accomplished by pushing each character on to ·11 off in the reverse o d
is finished, characters are popped off the Stack and they WI come r er.
Conversion of decimal number to binary is also done using S ack. t
• of Arithmetic Expressions: AStack is
2. Evaluation • a very e ffective data
. structure . for evaluating
.
arithmetic expressions in programming languages. An arithmetic express10n consists of
operands and operators. It may also include parentheses l1.ke "Ie ft parenthesis" . and "ng · ht
parenthesis". Stack is used to evaluate these arithmetic expressions on the basis of operator
precedence (BEDMAS - Brackets off; Exponentiation; Division/Multiplication; Addition/
Subtraction).
3. Processing Function Calls: The compilers use Stacks to store the previous state of a program
when a function is called or during recursion.
4. Backtracking: Backtracking is a form of recursion which involves choosing only one option
out of Lhe possibilities. Backtracking is used in a large number of puzzles like Sudoku and
in optimization problems such as knapsack.
5. Undo Mechanism in Text Editors: This operation is accomplished by keeping all text changes
in a Stack.

5.4 QUEUE*
In the previous topics, we have discussed implementation
of Stack. Now, we will learn implementation of Queue with
Python list.

Queues are similar to Stacks in that a Queue also consists of


a sequence of items (a linear list), but there ar_e.re.st&iatio,,._
~ - L . ..
a maximum of 50 concurrent requests to view resu t(s). So, to serve thousan s o user

i requests, a Queue would be the most appropriate data structure to use.


5. Simulating Wait: Call centre phone systems use a Queue to hold people in line until a customer
representative gets free.
6. Playlist Ordering: Buffers on MP3 players and portable CD players, iPod playlists, etc., add
songs to the end and play from the front of the list.

f MEMORY BYTES
► A list is a collection of elements which are stored in a sequence.
► A Stack is a linear structure implemented in LIFO {Last In, First Out) manner where insertions and deletions take
place only at one end, i.e., the Stack's top.
► An insertion in a Stack is called pushing and a deletion from a Stack is called popping.
► A Queue is a linear structure implemented in FIFO (first in, first out) manner where insertions can occur only at
the rear end and deletions can occur only at the front end.
► Traversal of a list or Stack or a Queue means visiting each element of the list.
► A Queue is a container of objects that are inserted and deleted according to the FIFO principle.
► Inserting an element in a Queue is called Enqueue.
► Deleting an element from the Queue is called Dequeue.
► When a Queue is implemented with the help of a list, it is termed as a Linear Queue.

OBJECTIVE TYPE QUESTIONS = = = = = = = = = = = = = = = = == = =

=ed 1. Fill in the blanks.


(a) .................... means organization of data.
ng
(b) A data structure has well defined ............ .. , .. .. .......... and .............. .
le.
(c) A .......................... is a linear list, also known as LIFO list.

You might also like