Sword refers to Offer 30. Stack LCOF containing min function

class MinStack {
public:
    MinStack() {
    }

    void push(int x) {
        stack.push(x);
        
        if (min_stack.empty() || min_stack.top() >= x) {
            min_stack.push(x);
        }
    }

    void pop() {
        if (!stack.empty()) {
            if (stack.top() == min_stack.top()) {
                min_stack.pop();
            }
            stack.pop();
        }
    }

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

    int min() {
        return min_stack.top();
    }



private:
    stack<int> stack, min_stack;
};

Guess you like

Origin blog.csdn.net/jcl314159/article/details/119573012