stack implementation:1
(WithOut Using Functions)
To maintain elements using a stack
Operations:
Addition of elements (PUSH)
Deletion of elements (POP)
Traversal of elements (DISPLAY)
Creation of empty stack
s=[]
Push operation
a=input(“Enter any element “)
s.append(a)
Pop operation
if(s==[]):
print(“Underflow / stack is empty”)
else:
print(“poped element is “,s.pop())
To check stack is empty or not
if(s==[]):
print(“stack is empty”)
else:
print(“stack is not empty”)
Travesal operation
n=len(s)
for i in range(n-1,-1,-1):
print(s[i])
Source Code
#stack implementation s=[] while True: print("1. Push"); print("2. Pop"); print("3. Traversal") print("4. Exit") ch=int(input("Enter your choice ")) if(ch==1): a=input("Enter any element ") s.append(a) elif(ch==2): if(s==[]): print("Underflow / stack is empty") else: print("poped element is ",s.pop()) elif(ch==3): n=len(s) for i in range(n-1,-1,-1): print(s[i]) elif(ch==4): print("End") break else: print("Invalid choice")
Output:
1. Push 2. Pop 3. Traversal 4. Exit Enter your choice 1 Enter any element 10 1. Push 2. Pop 3. Traversal 4. Exit Enter your choice 3 10 1. Push 2. Pop 3. Traversal 4. Exit Enter your choice 1 Enter any element 20 1. Push 2. Pop 3. Traversal 4. Exit Enter your choice 3 20 10 1. Push 2. Pop 3. Traversal 4. Exit Enter your choice 1 Enter any element hello 1. Push 2. Pop 3. Traversal 4. Exit Enter your choice 3 hello 20 10 1. Push 2. Pop 3. Traversal 4. Exit Enter your choice 2 poped element is hello 1. Push 2. Pop 3. Traversal 4. Exit Enter your choice 3 20 10 1. Push 2. Pop 3. Traversal 4. Exit Enter your choice 4 End >>>