0% found this document useful (0 votes)
64 views2 pages

Stack Operations - 1

The document describes a program that implements a stack using a list of integers in Python. It defines functions for pushing, popping, peeking at the top element, and displaying the stack. The main program runs a loop that prompts the user to select an operation and calls the corresponding function until the user chooses to exit. It provides sample output showing the stack being populated with pushes, an element being popped off, peeking at the top, and displaying the full stack contents.

Uploaded by

vimala
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)
64 views2 pages

Stack Operations - 1

The document describes a program that implements a stack using a list of integers in Python. It defines functions for pushing, popping, peeking at the top element, and displaying the stack. The main program runs a loop that prompts the user to select an operation and calls the corresponding function until the user chooses to exit. It provides sample output showing the stack being populated with pushes, an element being popped off, peeking at the top, and displaying the full stack contents.

Uploaded by

vimala
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/ 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