LEETCODE-MinStack

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.

两个栈来实现,其中一个odinarystack进行正常的push,pop,top操作,另一个minstack来存储每次压栈后最小的值

class MinStack {
private:
    stack<int> odinarystack;
    stack<int> minstack;
public:
    void push(int x) {
        odinarystack.push(x);
        if(minstack.empty() || x <= minstack.top()){
            minstack.push(x);
        }
    }

    void pop() {
        if(!odinarystack.empty()){
            if(odinarystack.top() == minstack.top())
                minstack.pop();
            odinarystack.pop();
        }
    }

    int top() {
        if(!odinarystack.empty())
            return odinarystack.top();
        else
            return NULL;
    }

    int getMin() {
        if(!minstack.empty())
            return minstack.top();
        else
            return NULL;
    }
};
阅读更多
个人分类: leetcode
想对作者说点什么? 我来说一句

不良信息举报

LEETCODE-MinStack

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭