forked from shwetagarg-dev/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspecial_stack.py
More file actions
63 lines (50 loc) · 2.06 KB
/
special_stack.py
File metadata and controls
63 lines (50 loc) · 2.06 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
''' Design a stack which holds an integer value such that getMinimum() function should return the minimum element in the stack.
Implement popMin() function which would pop minimum element from the original stack. O(1) implementation was required.'''
from llist import dllist
class SpecialStack:
def __init__(self):
self.main_stack = dllist()
self.min_stack = []
def push(self, data):
node = self.main_stack.append(data)
if len(self.min_stack) == 0:
self.min_stack.append(node)
elif data < self.min_stack[-1].value:
self.min_stack.append(node)
def pop(self):
if self.main_stack:
data = self.main_stack.pop()
if data == self.min_stack[-1].value:
self.min_stack.pop()
return data
else:
return "stack is empty"
def get_minimum(self):
if self.main_stack:
return self.min_stack[-1].value
else:
return "stack is empty"
''' Method is not complete
it does not handle the case when the last min element is deleted'''
def pop_minimum(self):
if self.main_stack:
data = self.main_stack.remove(self.min_stack[-1])
self.min_stack.pop()
return data
else:
return "stack is empty"
def main():
stack = SpecialStack()
stack.push(5)
stack.push(8)
stack.push(3)
stack.push(2)
stack.push(6)
print stack.main_stack, "\t", stack.min_stack, "\n"
print "Popped :", stack.pop(), "\t", stack.main_stack, "\t", stack.min_stack, "\n"
print "Popped :", stack.pop(), "\t", stack.main_stack, "\t", stack.min_stack, "\n"
print "Min element in stack is:", stack.get_minimum(), "\n"
print "Popped min element in stack:", stack.pop_minimum(), "\t", stack.main_stack, "\t", stack.min_stack, "\n"
print "Popped min element in stack:", stack.pop_minimum(), "\t", stack.main_stack, "\t", stack.min_stack, "\n"
if __name__ == "__main__":
main()