-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0155_Min_Stack.py
More file actions
40 lines (32 loc) · 988 Bytes
/
0155_Min_Stack.py
File metadata and controls
40 lines (32 loc) · 988 Bytes
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
class StackElement:
def __init__(self, val, minimum):
self.val = val
self.minimum = minimum
class MinStack:
def __init__(self):
self.stack = []
def push(self, val: int) -> None:
if not self.stack:
minimum = val
else:
prev_minimum = self.stack[-1].minimum
minimum = min(val, prev_minimum)
self.stack.append(StackElement(val, minimum))
def pop(self) -> None:
if not self.stack:
raise Exception("Empty stack!")
self.stack.pop()
def top(self) -> int:
if not self.stack:
raise Exception("Empty stack!")
return self.stack[-1].val
def getMin(self) -> int:
if not self.stack:
raise Exception("Empty stack!")
return self.stack[-1].minimum
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()