1. 程式人生 > >155. Min Stack

155. Min Stack

getmin 棧

155. Min Stack

#!/usr/bin/env python
class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
        self.minStack = []

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        self.stack.append(x)
        if not self.minStack:
            self.minStack.append(x)
        else:
            top = self.minStack[-1]
            if top >= x:
                self.minStack.append(x)
    #
    def pop(self):
        """
        :rtype: void
        """
        if self.stack:
            x = self.stack.pop()
            top = self.minStack[-1]
            if x == top:
                return self.minStack.pop()

    def top(self):
        """
        :rtype: int
        """
        if self.stack:
            return self.stack[-1]

    def getMin(self):
        """
        :rtype: int
        """
        if self.minStack:
            return self.minStack[-1]


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

155. Min Stack