Skip to content

Commit 554af6d

Browse files
committed
min stack solution
1 parent 289e99b commit 554af6d

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

solutions/155 - Min Stack.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import sys
2+
3+
4+
# implementation of queue data structure from scratch using list
5+
class Node:
6+
def __init__(self, data=None, next=None):
7+
self.data = data
8+
self.next = next
9+
10+
11+
class MinStack:
12+
def __init__(self):
13+
self.head = None
14+
15+
def __repr__(self):
16+
# traverse stack and print all values
17+
curr = self.head
18+
nodes_list = []
19+
while curr:
20+
nodes_list.append(str(curr.data))
21+
curr = curr.next
22+
nodes_list.append('None')
23+
return ', '.join(nodes_list)
24+
25+
def pop(self):
26+
# remove node from head
27+
current = self.head
28+
self.head = current.next
29+
current = None
30+
31+
def push(self, x):
32+
# insert new node between head and first element in the list
33+
new_node = Node(data=x) # initialize new node
34+
new_node.next = self.head
35+
self.head = new_node
36+
37+
def top(self):
38+
try:
39+
top = self.head.data
40+
except AttributeError:
41+
top = 'Stack is empty'
42+
return top
43+
44+
def getMin(self):
45+
if self.head is None:
46+
return None
47+
48+
minimum = sys.maxsize
49+
current = self.head
50+
while current is not None:
51+
if minimum > current.data:
52+
minimum = current.data
53+
current = current.next
54+
return minimum

0 commit comments

Comments
 (0)