Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.
class MinStack {
private:
    stack<int> data;
    stack<int> minStk;
public:
    void push(int x) {
        data.push(x);
        if(x <= getMin())
            minStk.push(x);
    }

    void pop() {
        if(!data.empty())
        {
            if(data.top() == minStk.top())
            {
                minStk.pop();
            }
            data.pop();
        }
    }

    int top() {
        if(!data.empty())
            return data.top();
        return 0;
    }

    int getMin() {
        if(!minStk.empty())
            return minStk.top();
        return INT_MAX;
    }
};

 

posted on 2015-01-08 18:58  风云逸  阅读(54)  评论(0)    收藏  举报