Skip to content

Commit eca0711

Browse files
Added a program to implement Stack datastructure
1 parent eecdc8f commit eca0711

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

algorithms/Stack.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"""
2+
Author: Jay Paliwal
3+
Desc: And implementation of the stack data structure using arrays.
4+
"""
5+
6+
class Stack:
7+
8+
def __init__(self,size):
9+
self.stack=[]
10+
self.size=size
11+
self.top=-1
12+
13+
def push(self):
14+
if self.top>=self.size-1:
15+
print("Stack overflow")
16+
else:
17+
val=int(input("Enter the value to be pushed: "))
18+
self.top+=1
19+
self.stack.insert(0,val)
20+
21+
def pop(self):
22+
if self.top<=-1:
23+
print("Stack underflow")
24+
else:
25+
self.top-=1
26+
print("Popped element: ",self.stack.pop(0))
27+
28+
def peek(self):
29+
if self.top==-1:
30+
print("Stack empty")
31+
else:
32+
print("Elemet at the top is: ",self.stack[0])
33+
34+
def display(self):
35+
if self.top==-1:
36+
print("Stack emppty.")
37+
else:
38+
print("The stack elements are: ",*self.stack)
39+
40+
def empty(self):
41+
if self. top==-1:
42+
print("Stack is already empty")
43+
else:
44+
print("The elements deleted from the stack are: ",*self.stack)
45+
self.top=-1
46+
47+
48+
stack_size=int(input("Enter the size of the Stack: "))
49+
stk=Stack(stack_size)
50+
while True:
51+
fn=input("\nMenu:\n1. Enter 'push' to push new element\n2. Enter 'pop' to pop top element\n3. Enter 'peek' to view top elemnt\n4. Enter 'display' to display all elemts of stack\n5 Enter 'empty' to display current stack elemets and clear the stack\n6. Enter 'exit' to end program\n")
52+
print("\n")
53+
if fn=="exit":
54+
break
55+
elif fn=="push":
56+
stk.push()
57+
elif fn=="pop":
58+
stk.pop()
59+
elif fn=="peek":
60+
stk.peek()
61+
elif fn=="display":
62+
stk.display()
63+
elif fn=="empty":
64+
stk.empty()
65+
else:
66+
print("Enter a valid input")
67+
68+

0 commit comments

Comments
 (0)