You are on page 1of 2

16.

STACK OPERATIONS - 1
AIM :
To implement a Stack using a list of integers and performing the related operations
using user defined functions.
def Push():
stk.append(int(input("Enter an item to be added")))
print("Current stack is ",stk[::-1],"\n")
top=len(stk)-1
def Pop():
if stk==[]:
print("Underflow")
else:
print("popped item",stk.pop())
if len(stk)==0:
top=None
else: top=len(stk)-1
def Peek():
if stk==[]:
print("Underflow")
else:
if len(stk)==0:
top=None
else:
top=len(stk)-1
print("top most item ",stk[top])
def display():
if stk==[]:
print("Stack is empty!\n")
else:
top=len(stk)-1
print("Stack is:-")
for i in range(top,-1,-1):
print(stk[i])
stk=[]
top=None
while True:
print("STACK OPERATIONS:\n1. Push\n2. Pop\n3. Peek\n4. Display stack\n5. Exit")
ch=int(input("Enter your choice: "))
if ch==1: Push()
elif ch==2: Pop()
elif ch==3: Peek()
elif ch==4: display()
elif ch==5:
print("THANK YOU :)")
break
else: print("Invalid choice")
OUTPUT
STACK OPERATIONS:
1. Push
2. Pop
3. Peek
4. Display stack
5. Exit
Enter your choice: 1
Enter an item to be added23
Current stack is [23]
Enter your choice: 1
Enter an item to be added34
Current stack is [34, 23]
Enter your choice: 1
Enter an item to be added45
Current stack is [45, 34, 23]
Enter your choice: 2
popped item 45
Enter your choice: 3
top most item 34
Enter your choice: 4
Stack is:-
34
23
Enter your choice: 5
THANK YOU :)

You might also like