Implementation of Stack in Python List
#Function to check
the stack is empty or not.
def
isEmpty(stk):
if stk==[]:
return True
else:
return False
#Function to push the value in the stack.
def
Push(stk,val):
stk.append(val)
top=len(stk)-1
#Function to remove
the value from the top of the stack
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
val=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return val
#Function to inspect
the position of the top to insert value in stack
def Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top=len(stk)-1
return stk[top]
#Function to display
the stack values
def
Display(stk):
if isEmpty(stk):
print("Stack is Empty, Nothing to
display")
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])
#__main__
Stack=[] #Initially stack is
empty list
top=None
while True:
print("STACK OPERATION MENU")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
ch=int(input("Enter your choice:
"))
if ch==1:
n=int(input("Enter value: "))
Push(Stack,n)
elif ch==2:
n=Pop(Stack)
if n=="Underflow":
print("Underflow!!! Stack is
empty")
else:
print("Popped value
is:",n)
elif ch==3:
n=Peek(Stack)
if n=="Underflow":
print("Underflow!!! Stack is
empty")
else:
print("Topmost value
is:",n)
elif ch==4:
Display(Stack)
elif ch==5:
break;
else:
print("Invalid choice")
STACK OPERATION MENU
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice:
No comments
Post your comments