面试题 03.02. 栈的最小值

面试题 03.02. 栈的最小值

思路:两个栈,一个存数据,一个存当前最小值

class MinStack {
public:
    stack<int> s1;
    stack<int> s2;
    MinStack() {
    }
    void push(int x) {
        s1.push(x);
        if(s2.size()==0 || x<s2.top()) s2.push(x);
        else s2.push(s2.top());
    }
    void pop() {
        s1.pop();
        s2.pop();
    }
    int top() {
        return s1.top();
    }
    int getMin() {
        return s2.top();
    }
};
发布了248 篇原创文章 · 获赞 29 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_38603360/article/details/105157213