Skip to content

Instantly share code, notes, and snippets.

@openroc
Last active September 26, 2017 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save openroc/196642a254a542e4e80f to your computer and use it in GitHub Desktop.
Save openroc/196642a254a542e4e80f to your computer and use it in GitHub Desktop.
MinStack(Python)
class MinStack:
def __init__(self):
self.L=[]
self.count = 0
def pop(self):
self.count -= 1
return self.L.pop()[0]
def push(self,x):
minval = self.L[-1][1] if self.count > 0 else x
d = (x,x) if x < minval else (x, minval)
self.L.append(d)
self.count += 1
def top(self):
return self.L[-1][0]
def getMin(self):
return self.L[-1][1]
if __name__ == '__main__':
s = MinStack()
s.push(5)
s.push(4)
s.push(3)
s.push(2)
s.push(1)
s.push(2)
s.push(3)
s.push(4)
s.push(5)
for n in xrange(s.count):
print 'min:', s.getMin()
print 'pop:', s.pop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment