0% found this document useful (0 votes)
2 views

stack

The document contains a Python implementation of a stack data structure with operations such as Push, Pop, Peek, and Display. It includes a main loop that allows users to interactively perform stack operations until they choose to exit. The code also handles underflow conditions when attempting to pop or peek from an empty stack.

Uploaded by

nothinga921
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

stack

The document contains a Python implementation of a stack data structure with operations such as Push, Pop, Peek, and Display. It includes a main loop that allows users to interactively perform stack operations until they choose to exit. The code also handles underflow conditions when attempting to pop or peek from an empty stack.

Uploaded by

nothinga921
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

def Push(stk,a):

stk.append(a)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
it=stk.pop()
if (len(stk)==0):
top=None
else:
top=len(stk)-1
return it
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])

def isEmpty(stk):
if stk==[]:
return True
else:
return False
#main
stack=[]
top=None
while True:
print("stack operation")
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=int(input("enter the element to push"))
Push(stack,item)
elif (ch==2):
item=Pop(stack)
if(item=="underflow"):
print("underflow ! stack is empty")
print("popped item", item)
elif(ch==3):
item=Peek(stack)
if(item=="underflow"):
print("underflow: stack is empty")
print("topmost item is ",item)
elif(ch==4):
Display(stack)
elif(ch==5):
break
else:
print("invalid choice")

You might also like