0% found this document useful (0 votes)
6 views2 pages

Stack Implementation Python Code

This document provides a Python implementation of a stack data structure with operations such as push, pop, peek, and display. It includes functions to check if the stack is empty, handle overflow and underflow conditions, and interact with the user through a menu-driven interface. The stack has a fixed size of 5 and utilizes a global variable to track the top index.

Uploaded by

syashvardhan28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Stack Implementation Python Code

This document provides a Python implementation of a stack data structure with operations such as push, pop, peek, and display. It includes functions to check if the stack is empty, handle overflow and underflow conditions, and interact with the user through a menu-driven interface. The stack has a fixed size of 5 and utilizes a global variable to track the top index.

Uploaded by

syashvardhan28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Stack Implementation Python Code

#Check stack is empty or not


def isEmpty(stk):
global top
if top==-1:
return True
else:
return False

#Push Operation Function


def Push(stk,item):
global top
if top==size-1:
return "Overflow"
else:
top=top+1
print(top)
[Link](item)
return "PushSuccess"

#Pop Operation Function


def Pop(stk):
global top
if isEmpty(stk):
return "Underflow"
else:
item=[Link]()
if len(stk)==0:
top=-1
else:
top=top-1
return item

#Peek Operation Function


def Peek(stk):
global top
if isEmpty(stk):
print("Underflow")
else:
return stk[top]

#Display Operation Function


def Display(stk):
if isEmpty(stk):
print("Stack is Empty")
else:
for i in range(len(stk)):
print(stk[i],end=" ")
#__main_
Stack=[]
top=-1
size=5

while True:
print("STACK OPERATIONS")
print("1. PUSH OPERATION")
print("2. POP OPERATION")
print("3. PEEK OPERATION")
print("4. DISPLAY OPERATION")
print("5. EXIT")
ch=int(input("Enter your choice : "))
if ch==1:
item=int(input("Enter Item : "))
msg=Push(Stack,item)
if msg=="Overflow":
print("Overflow! Stack is alredy full")
else:
print("Item Pushed in stack")
elif ch==2:
item=Pop(Stack)
if item=="Underflow":
print("Underflow!Stack is empty.!")
else:
print("Item Popped 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!")

You might also like