-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMin_stack.py
56 lines (49 loc) · 1.31 KB
/
Min_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
class Newnode:
def __init__(self, data):
self.data = data
self.next = None
class MinStack:
def __init__(self):
self.head = None
self.mi = None
def push(self, x):
temp = Newnode(x)
if self.mi==None and temp!=None:
self.mi = temp.data
temp.next = self.head
self.head = temp
else:
if temp.data<self.mi:
temp.data = 2*(temp.data) - self.mi
self.mi = x
temp.next = self.head
self.head = temp
else:
temp.next = self.head
self.head = temp
def pop(self):
temp = self.head
if temp!=None:
if temp.data < self.mi:
self.mi = 2*(self.mi)-temp.data
self.head = self.head.next
if self.head==None:
self.mi = None
temp = None
def top(self):
if self.head != None:
x = self.head.data
if x<self.mi:
x = self.mi
else:
x = None
return x
def getMin(self):
return self.mi
stk = MinStack()
stk.push(10)
stk.push(12)
stk.push(8)
print(stk.getMin())
stk.pop()
print(stk.getMin())