forked from raviprakashdev/simplePythonProgram
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.py
More file actions
68 lines (57 loc) · 1.79 KB
/
Stack.py
File metadata and controls
68 lines (57 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
Author: Jay Paliwal
Desc: And implementation of the stack data structure using arrays.
"""
class Stack:
def __init__(self,size):
self.stack=[]
self.size=size
self.top=-1
def push(self):
if self.top>=self.size-1:
print("Stack overflow")
else:
val=int(input("Enter the value to be pushed: "))
self.top+=1
self.stack.insert(0,val)
def pop(self):
if self.top<=-1:
print("Stack underflow")
else:
self.top-=1
print("Popped element: ",self.stack.pop(0))
def peek(self):
if self.top==-1:
print("Stack empty")
else:
print("Elemet at the top is: ",self.stack[0])
def display(self):
if self.top==-1:
print("Stack emppty.")
else:
print("The stack elements are: ",*self.stack)
def empty(self):
if self. top==-1:
print("Stack is already empty")
else:
print("The elements deleted from the stack are: ",*self.stack)
self.top=-1
stack_size=int(input("Enter the size of the Stack: "))
stk=Stack(stack_size)
while True:
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")
print("\n")
if fn=="exit":
break
elif fn=="push":
stk.push()
elif fn=="pop":
stk.pop()
elif fn=="peek":
stk.peek()
elif fn=="display":
stk.display()
elif fn=="empty":
stk.empty()
else:
print("Enter a valid input")