forked from Rajspeaks/Daily-Coding-DS-ALGO-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack in Python
122 lines (109 loc) · 2.29 KB
/
Stack in Python
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner
class Node:
def __init__(self, data):
self.data = data
self.ref = None
class Stack:
def __init__(self):
self.__head = None
self.__size = 0
def push(self, data):
# adds an element at the beginning
self.__size += 1
new_node = Node(data)
new_node.ref = self.__head
self.__head = new_node
def pop(self):
# deletes element from beginning
if self.isEmpty():
print("Stack is empty.")
return
self.__size -= 1
print(self.__head.data)
self.__head = self.__head.ref
def top(self):
# prints the topmost element, i.e, head in the case of LL
if self.isEmpty():
print("Stack is empty.")
return
print(self.__head.data)
def isEmpty(self):
return(self.__size == 0)
def display(self):
# displays the stack from top to bottom
n = self.__head
if n is None:
print("Empty!")
return
while n is not None:
print(n.data)
n = n.ref
if __name__ == "__main__":
s2 = Stack()
print("Enter values to push in the stack: ")
value = [ele for ele in input().split()]
for i in range(len(value)):
s2.push(value[i])
print("The stack is:")
s2.display()
print('\nThe first element which is removed is: ')
s2.pop()
print('\nThe topmost element of the stack is:')
s2.top()
print("\nThe stack is:")
s2.display()
"""Time-Complexity of the program:
push(): O(1)
pop(): O(1)
top(): O(1)
display(): O(N)
"""
"""Test-Cases:
>>>
Enter values to push in the stack:
10 15 23 42
The stack is:
42
23
15
10
The first element which is removed is:
42
The topmost element of the stack is:
23
The stack is:
23
15
10
>>>
Enter values to push in the stack:
Jack
The stack is:
Jack
The first element which is removed is:
Jack
The topmost element of the stack is:
Stack is empty.
The stack is:
Empty!
>>>
Enter values to push in the stack:
Jack 1 QWERTY 22 key 87
The stack is:
87
key
22
QWERTY
1
Jack
The first element which is removed is:
87
The topmost element of the stack is:
key
The stack is:
key
22
QWERTY
1
Jack
"""