-
Notifications
You must be signed in to change notification settings - Fork 4
/
Stack.py
60 lines (48 loc) · 1.12 KB
/
Stack.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
class Node :
def __init__(self, data, next = None) -> None:
self.data = data
self.next = next
class Stack:
def __init__(self) -> None:
self.head = None
self.sz = 0
def size(self) -> int :
return self.sz
def isEmpty(self) -> bool :
return self.size() == 0
def push(self, val) :
self.head = Node(val, self.head)
self.sz += 1
def pop(self) :
if self.isEmpty() :
raise Exception("Stack Underflow")
data = self.head.data
temp = self.head
self.head = self.head.next
del temp
self.sz -= 1
return data
def top(self) :
if self.isEmpty() :
raise Exception("Stack Underflow")
return self.head.data
def __str__(self) :
st = []
trav = self.head
while trav :
st.append(str(trav.data))
trav = trav.next
return '->'.join(st)
#Test
st = Stack()
st.push(5)
st.push(10)
print(st)
print(st.size())
st.push(11)
st.push(13)
print(st)
print(st.pop())
print(st)
print(st.top())
print(st)