Skip to content

Instantly share code, notes, and snippets.

@yokiy
Created July 2, 2014 21:45
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 yokiy/7ab19f4b78de60a32eb5 to your computer and use it in GitHub Desktop.
Save yokiy/7ab19f4b78de60a32eb5 to your computer and use it in GitHub Desktop.
cc 3.2
#3.2 How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.
from stack import Stack, Node
class stackmin(Stack):
def __init__(self):
Stack.__init__(self)
self.min = Stack()
self.minItem = None
def push(self, item):
Stack.push(self,item)
if self.minItem is not None:
if self.minItem < item:
self.minItem = item
else:
self.minItem = item
self.min.push(self.minItem)
def pop(self):
Stack.pop(self)
self.min.pop()
def printStack(self):
Stack.printStack(self)
def stackMin(self):
print 'the min:', self.min.top.item
#test
stack = stackmin()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.stackMin()
stack.pop()
stack.stackMin()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment