剑指 Offer 30. 包含min函数的栈

剑指 Offer 30. 包含min函数的栈_第1张图片

class MinStack {
private:
    stack<int> st,minst;
public:
    /** initialize your data structure here. */
    MinStack() {
        minst.push(INT_MAX);
    }
    
    void push(int x) {
        st.push(x);
        if(minst.top() > x || minst.empty())
            minst.push(x);
        else
            minst.push(minst.top());
    }
    
    void pop() {
        st.pop();
        minst.pop();
    }
    
    int top() {
        return st.top();
    }
    
    int min() {
        return minst.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();
 */

题解:
考察的栈的基本使用
剑指 Offer 30. 包含min函数的栈_第2张图片

你可能感兴趣的:(c++,算法,数据结构)