剑指OFFER----面试题30. 包含min函数的栈

链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/

代码:

class MinStack {
public:
    /** initialize your data structure here. */
    
    stack<int> s1, s2;
    
    MinStack() {
 
    }
    
    void push(int x) {
        s1.push(x);
        if(s2.empty() || x < s2.top()){
            s2.push(x);
        }
        else{
            s2.push(s2.top());
        }
    }
    void pop() {
        s1.pop();
        s2.pop();
    }
    int top() {
        return s1.top();
    }
    int min() {
        return s2.top();
    }

};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack* obj = new MinStack();
 * obj->push(x);
 * obj->pop();
 * int param_3 = obj->top();
 * int param_4 = obj->min();
 */
原文地址:https://www.cnblogs.com/clown9804/p/12371869.html