forked from anmol/algorithm_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspecial_stack.py
More file actions
52 lines (40 loc) · 1.18 KB
/
Copy pathspecial_stack.py
File metadata and controls
52 lines (40 loc) · 1.18 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
#!/usr/bin/env python2.7
from stack import Stack
from node import Node
# all operations must be O(1)
class SpecialStack(Stack):
def __init__(self):
super(SpecialStack, self).__init__()
self.min_stack = Stack()
def push(self, n):
if super(SpecialStack, self).is_empty():
print "stack is empty"
super(SpecialStack, self).push(n)
self.min_stack.push(Node(n.data))
else:
super(SpecialStack, self).push(n)
last_min = self.min_stack.pop()
self.min_stack.push(Node(last_min.data))
if last_min.data > n.data:
self.min_stack.push(Node(n.data))
else:
self.min_stack.push(Node(last_min.data))
def pop(self):
item = super(SpecialStack, self).pop()
self.min_stack.pop()
return item
def get_min(self):
return self.min_stack.head.data
if __name__ == "__main__":
s = SpecialStack()
s.push(Node(10))
s.push(Node(20))
s.push(Node(40))
s.push(Node(30))
s.push(Node(80))
s.print_stack()
print s.get_min()
s.pop()
s.pop()
# s.print_stack()
print s.get_min()