Min Stack

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        min_val = INT_MAX;
    }

    void push(int x) {
        if (x <= min_val) {
            st.push(min_val);//存一下前一个min
            min_val = x;
        }
        st.push(x);
    }

    void pop() {
        int t = st.top(); st.pop();
        if (t == min_val) { //如果cur min被pop了
            min_val = st.top(); //restore prev min
            st.pop(); 
        }
    }

    int top() {
        return st.top();
    }

    int getMin() {
        return min_val;
    }
private:
    int min_val;
    stack<int> st;
};

results matching ""

    No results matching ""