Last active
September 26, 2017 03:10
-
-
Save openroc/196642a254a542e4e80f to your computer and use it in GitHub Desktop.
MinStack(Python)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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