LeetCode:Min Stack(待更新)

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:  
    std::stack<int> stack;  
    std::stack<int> min_stack;  
public:  
    void push(int x) {  
        stack.push(x);  
        if (min_stack.empty() || ((!min_stack.empty()) && x <= min_stack.top())) {  
            min_stack.push(x);  
        }  
    }  
      
    void pop() {  
        if (!stack.empty()) {  
            if (stack.top() == min_stack.top())  
                min_stack.pop();  
            stack.pop();  
        }  
    }  
      
    int top() {  
        if (!stack.empty())  
            return stack.top();  
    }  
      
    int getMin() {  
        if (!min_stack.empty())  
            return min_stack.top();  
    }  
};

 

posted @ 2015-08-04 15:28  尾巴草  阅读(133)  评论(0编辑  收藏  举报