-
Notifications
You must be signed in to change notification settings - Fork 1k
/
stack_using_list.py
108 lines (98 loc) · 2.27 KB
/
stack_using_list.py
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#Python program to implement stack using list (array)
class Stack:
#constructor
def __init__(self):
self.stack = []
self.top = None
#inserting on top
def push(self, value):
self.stack.append(value)
self.top = len(self.stack)-1
#check if stack is empty
def is_empty(self):
if self.stack == []:
print("Stack is empty !")
else:
print("Stack not empty yet")
#removing an element from top
def pop(self):
if self.stack == []:
print("Underflow")
else:
value = self.stack.pop()
self.top = len(self.stack)
print("The popped element is ", value)
#get the top element
def peek(self):
if self.stack == []:
print("Underflow")
else:
print("Top element is : " , self.stack[-1])
#display stack elements
def display(self):
if self.stack == []:
print("Underflow")
else:
print("Stack elements are :")
for i in range(self.top, -1, -1):
print(self.stack[i])
#executable code
if __name__ == '__main__':
s = Stack()
print(" MENU ")
print("1. Push\n2. Pop\n3. Peek\n4. Empty\n5. Display\n6. Exit")
while True:
ch = int(input("Enter your choice : "))
if ch == 1:
val = int(input("Enter a value : "))
s.push(val)
elif ch == 2:
s.pop()
elif ch == 3:
s.peek()
elif ch == 4:
s.is_empty()
elif ch == 5:
s.display()
elif ch == 6:
break
else:
print("Wrong choice")
"""
SAMPLE I/O:
MENU
1. Push
2. Pop
3. Peek
4. Empty
5. Display
6. Exit
Enter your choice : 1
Enter a value : 10
Enter your choice : 1
Enter a value : 20
Enter your choice : 1
Enter a value : 30
Enter your choice : 5
Stack elements are :
30
20
10
Enter your choice : 3
Top element is : 30
Enter your choice : 2
The popped element is 30
Enter your choice : 2
The popped element is 20
Enter your choice : 2
The popped element is 10
Enter your choice : 4
Stack is empty !
Enter your choice : 6
Time Complexity:
Push : O(1)
Pop : O(1)
Peek : O(1)
Empty : O(1)
Space Complexity: O(n)
"""