Professional Documents
Culture Documents
Chapter: Data Strucures in Python: Stack and Queue (List Implementation)
Chapter: Data Strucures in Python: Stack and Queue (List Implementation)
Introduction
A stack is a linear data structure, which follows the principle of Last In First Out
(LIFO). Consider a pile (stack) of books on a table. One book may be added to the
pile or taken away from the pile at a time. The book which was placed last on the
pile (Last In) is the one which can be taken out (First Out) from the pile. An index
(called TOP) tracks the elements in the stack. TOP is initialized as -1 and
incremented as and when an element is added (known as PUSH operation) or
decremented when an element is deleted (known as POP operation) from the
stack. At any given point of time, only the top element of the stack can be seen.
There is a capacity defined for a stack in terms of the maximum elements it can
hold. When the maximum capacity is reached, one more PUSH operation gives an
error known as OVERFLOW. Similarly removing an element from an empty stack is
results in UNDERFLOW error.
STACK OPERATIONS:
A stack is described with the following operations. Each of these operations are
defined by the programmer.
NOTE:
The list methods make it very easy to use a list as a stack, where the last element
added is the first element retrieved (“last-in, first-out”). To add an item to the
top of the stack, use append(). To retrieve an item from the top of the stack,
use pop() without an explicit index.
Example:
>>> stack = [3, 4, 5]
>>>stack.append(6)
>>>stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>>stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>>stack.pop()
6
>>>stack.pop()
5
>>> stack
[3, 4]
Program to implement a stack using list :
def push(mystack, item):
mystack.append(item)
def pop(mystack):
if len(mystack) == 0:
print ("Underflow")
else:
item = mystack.pop()
print(" Element popped is " ,item)
mystack = []
push(mystack ,5)
push(mystack ,15)
push(mystack ,25)
push(mystack ,35)
print(mystack)
pop(mystack)35
pop(mystack)25
pop(mystack)15
print(mystack)
push(mystack ,100)
print(mystack)
pop(mystack)100
pop(mystack)5
print(mystack)
pop(mystack)
'''
Output :
[5, 15, 25, 35]
Element popped is 35
Element popped is 25
Element popped is 15
[5]
[5, 100]
Element popped is 100
Element popped is 5
[]
Underflow
'''
Solved example:-
1.Push
2.Pop
3.DISPLAY
Enter your choice: 1
Enter the item: 10
Do you want to continue(y/n)
1.Push
2.Pop
3.DISPLAY
Enter your choice: 1
Enter the item: 20
Do you want to continue(y/n)
1.Push
2.Pop
3.DISPLAY
Enter your choice: 3
20
10
Do you want to continue(y/n)
1.Push
2.Pop
3.DISPLAY
Enter your choice: 2
Deleted element is 20
Do you want to continue(y/n)
1.Push
2.Pop
3.DISPLAY
Enter your choice: 2
Deleted element is 10
Do you want to continue(y/n)
1.Push
2.Pop
3.DISPLAY
Enter your choice: 3
Stack empty
"""
OR (MENU DRIVEN PROGRAM FOR STACK AS A LIST)
s=[]
def stkpush(s):
if len(s)==100:
print("not willing to accept more than 100 values")
else:
v=int(input("enter a value:"))
s.append(v)
print("value pushed into stack")
def stkpop(s):
if len(s)!=0:
v=s.pop()
print("value popped=",v)
else:
print("cannot pop from an empty stack")
def stkdisplay(s):
for i in range(len(s)-1,-1,-1):
print(s[i])
while True:
print("""stack operations
1.Push values
2.Pop values
3.Display
4.Exit
""")
ch=int(input("enter a choice(1-4):"))
if ch==1:
stkpush(s)
elif ch==2:
stkpop(s)
elif ch==3:
stkdisplay(s)
elif ch==4:
print("Thanks for running the program")
break
else:
print("invalid choice")
P:2 Program to reverse a string using a stack
mystack.append(item)
def pop(mystack,item):
if len(mystack)==0:
print("underflow")
else:
item=mystack.pop()
return (item)
n=len(string)
for i in range(0,n,1):
push(mystack,string[i])
string=" "
item=' '
for i in range(0,n,1):
string+=pop(mystack,item)
return string
mystack=[]
string="MALAYALAM"
string=reverse(string, mystack)
P:3 Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this
list push all numbers divisible by 5 into a stack implemented by using a list. Display
the stack if it has at least one element, otherwise display appropriate error
message.
OR
Write a function in Python POP(Arr), where Arr is a stack implemented by a list of
numbers. The function returns the value deleted from the stack.
def PUSH(Arr):
Stack=[ ]
if len(Arr)!=0:
for i in Arr:
if i%5==0:
Stack.append(i)
if len(Stack)!=0:
for i in range(len(Stack)-1,-1,-1):
print(Stack[i])
else:
print("Empty Stack")
else:
print("Source List is empty")
return(Stack)
def POP(Arr):
x=-1
if len(Arr)==0:
print("Empty Stack")
else:
x=Arr.pop( )
return(x)
b=[10,7,5,18,21,25]
a=PUSH(b)
c=POP(a)
if c==-1:
print("Empty stack")
else:
print("Popped value : ",c)
Queue
A queue is a pile in which items are added on one end and removed from the
other. In this respect, a queue is like the line of customers waiting to get a ticket
in a movie counter. As customers arrive, they join the end of the queue while the
ticket issuer serves the customer at the head of the queue. As a result, a queue is
used when a sequence of activities must be done on a first-come, first-served
basis. Queue is a First-In-First-Out (FIFO) structure. When we add an element into
Queue is known as REAR and when we delete an element from queue is known as
FRONT.The queue operations are given below.
QUEUE OPERATIONS:
R=0,F=0
R=1, F=1, A
R=2, F=1 A B
R=3 ,F=1 A B C
R=4 ,F=1 A B C D
R= 5, F=1 A B C D E
R=5, F=2 B C D E
R=5 ,F= 3 C D E
R=5,F=4 D E
R=5 ,F=5 E
R= 0, F=0
Program to simulate the core operations of a queue using append and pop
operations of the list .
fruits = []
However, lists are not efficient for this purpose. While appends and pops from the
end of list are fast, doing inserts or pops from the beginning of a list is slow
(because all of the other elements have to be shifted by one).
def Delete(myQ):
if len(myQ) == 0:
print ("Underflow")
else:
item = myQ.pop(0)
print(" Element deleted is " ,item)
myQ = []
insert(myQ ,5)
insert(myQ ,15)
insert(myQ ,25)
insert(myQ ,35)
print(myQ)
Delete(myQ)
Delete(myQ)
print(myQ)
insert(myQ ,100)
print(myQ)
Delete(myQ)
Delete(myQ)
print(myQ) 100
Delete(myQ)
print(myQ)
Delete(myQ)
'''
Output :
[5, 15, 25, 35]
Element deleted is 5
Element deleted is 15
[25, 35]
[25, 35, 100]
Element deleted is 25
Element deleted is 35
[100]
Element deleted is 100
[]
Underflow
'''
Solved example:-
"""
*******
Example :1
mystack.append(item)
def pop(mystack,item):
if len(mystack)==0:
print("underflow")
else:
item=mystack.pop()
return item
while decnumber>0:
push(mystack,rem)
item=0
dec2bin(num,mystack)
OUTPUT
1 0 1 1 0 0 0 1 0
The function dec2bin can be modified to convert numbers with any base.