3.2 Stack min

来源:互联网 发布:linux sort 小数 编辑:程序博客网 时间:2024/06/06 00:46

Using extra stack to track minimum element.

class MinStack {public:    stack<int> s1;    stack<int> s2;    void push(int x) {        s1.push(x);        if(s2.empty() || x<= getMin()) s2.push(x);    }    void pop() {        if (s1.top() == getMin()) s2.pop();        s1.pop();    }    int top() {        return s1.top();    }    int getMin() {        return s2.top();    }};
0 0