stack: implmented as a list
top: integer having position of topmost element in Stack
def isEmpty(stk):
if stk==[]:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack Empty")
else:
top=len(stk)-1
print(stk[top],"<--top")
for a in range(top-1,-1,-1):
print(stk[a])
#_main_
stack=[] #initially stack is empty
top=None
while True:
print("Stack Operations")
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.Display Stack")
print("5.Exit")
ch=int(input("Enter your choice:"))
if ch==1:
item=eval(input("Enter item:"))
Push(stack,item)
elif ch==2:
item=Pop(stack)
if item=="Underflow":
print("Underflow!stack is empty!")
else:
print("Popped item is",item)
elif ch==3:
item=Peek(stack)
if item=="Underflow":
print("Underflow!stack is empty!")
else:
print("Topmost item is",item)
elif ch==4:
Display(stack)
elif ch==5:
break
else:
print("Invalid choice!")
Contents
Output
Stack Operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice:1
Enter item:45
Stack Operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice:2
Popped item is 45
Stack Operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice:1
Enter item:35
Stack Operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice:1
Enter item:46
Stack Operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice:3
Topmost item is 46
Stack Operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice:4
46 <–top
35
Stack Operations
1.Push
2.Pop
3.Peek
4.Display Stack
5.Exit
Enter your choice:5