-
Notifications
You must be signed in to change notification settings - Fork 0
/
getmin.py
98 lines (83 loc) · 2.53 KB
/
getmin.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
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return 'Node ({})'.format(self.value)
__repr__ = __str__
class Stack:
def __init__(self):
self.top = None
self.count = 0
self.minimum = None
def __str__(self):
temp = self.top
out = []
while temp:
out.append(str(temp.value))
temp = temp.next
out = '\n'.join(out)
return('Top {} \n\nStack : \n{}'.format(self.top.out))
def getMin(self):
if self.top is None:
return "Stack is empty"
else:
print("Minimum Element in the stack is: {}" .format(self.minimum))
def isEmpty(self):
if self.top == None:
return True
else:
return False
def __len__(self):
self.count = 0
tempNode = self.top
while tempNode:
tempNode = tempNode.next
self.count += 1
return self.count
def peek(self):
if self.top is None:
print('Stack is Empty')
else:
if self.top.value < self.minimum:
print('Top Most Element is : {}'.format(self.minimum))
else:
print('Top Most Element is : {}'.format(self.top.value))
def push(self,value):
if self.top is None:
self.top = Node(value)
self.minimum = value
elif value < self.minimum:
temp = (2 * value) - self.minimum
new_node = Node(temp)
new_node.next = self.top
self.top = new_node
self.minimum = value
else:
new_node = Node(value)
new_node.next = self.top
self.top = new_node
print('Number Inserted : {} '.format(value))
def pop(self):
if self.top is None:
print('Stack is empty')
else:
removedNode = self.top.value
self.top = self.top.next
if removedNode < self.minimum:
print("Top Most Element Removed :{} " .format(self.minimum))
self.minimum = ( ( 2 * self.minimum ) - removedNode )
else:
print ("Top Most Element Removed : {}" .format(removedNode))
#Driver Class
stack = Stack()
stack.push(3)
stack.push(5)
stack.getMin()
stack.push(2)
stack.push(1)
stack.getMin()
stack.pop()
stack.getMin()
stack.pop()
stack.peek()