Leetcode21: Min Stack

来源:互联网 发布:java移植安卓游戏 编辑:程序博客网 时间:2024/05/17 01:58

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



0 0
原创粉丝点击