Examples of Stack

Examples of Stack

Example:1

 

#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”)

 

 

Example:2

 

#stack implementation using functions
s=[]

def push():
a=input(“Enter any element to push “)
s.append(a)

def pop():
if(s==[]):
print(“Underflow / Stack in empty”)
else:
print(“poped element is “,s.pop())

def traverse():
n=len(s)
for i in range(n-1,-1,-1):
print(s[i])


while True:
print(“1. Push”);
print(“2. Pop”);
print(“3. Traversal”)
print(“4. Exit”)
ch=int(input(“Enter your choice “))
if(ch==1):
push()
elif(ch==2):
pop();
elif(ch==3):
traverse()
elif(ch==4):
print(“End”)
break
else:
print(“Invalid choice”)

 

Example:3

 

#stack implementation using functions
#program to create a stack of employee(empno,name,sal).
“””
push
pop
traverse

“””
employee=[]

def push():
empno=input(“Enter empno “)
name=input(“Enter name “)
sal=input(“Enter sal “)
emp=(empno,name,sal)
employee.append(emp)

def pop():
if(employee==[]):
print(“Underflow / Employee Stack in empty”)
else:
empno,name,sal=employee.pop()
print(“poped element is “)
print(“empno “,empno,” name “,name,” salary “,sal)

def traverse():
if not (employee==[]):
n=len(employee)
for i in range(n-1,-1,-1):
print(employee[i])
else:
print(“Empty , No employee to display”)


while True:
print(“1. Push”);
print(“2. Pop”);
print(“3. Traversal”)
print(“4. Exit”)
ch=int(input(“Enter your choice “))
if(ch==1):
push()
elif(ch==2):
pop();
elif(ch==3):
traverse()
elif(ch==4):
print(“End”)
break
else:
print(“Invalid choice”)