You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Desc: And implementation of the stack data structure using arrays.
4
+
"""
5
+
6
+
classStack:
7
+
8
+
def__init__(self,size):
9
+
self.stack=[]
10
+
self.size=size
11
+
self.top=-1
12
+
13
+
defpush(self):
14
+
ifself.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
+
defpop(self):
22
+
ifself.top<=-1:
23
+
print("Stack underflow")
24
+
else:
25
+
self.top-=1
26
+
print("Popped element: ",self.stack.pop(0))
27
+
28
+
defpeek(self):
29
+
ifself.top==-1:
30
+
print("Stack empty")
31
+
else:
32
+
print("Elemet at the top is: ",self.stack[0])
33
+
34
+
defdisplay(self):
35
+
ifself.top==-1:
36
+
print("Stack emppty.")
37
+
else:
38
+
print("The stack elements are: ",*self.stack)
39
+
40
+
defempty(self):
41
+
ifself. 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
+
whileTrue:
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")
0 commit comments