leetcode+ 最小栈,设计题,使用两个栈

点击打开链接

class MinStack {
public:
    stack s1, s2;
    /** initialize your data structure here. */
    MinStack() {
        
    }
    void push(int x) {
        s1.push(x);
        if(s2.empty() || x <=s2.top()) s2.push(x);
    }
    
    void pop() {
        if(s1.top()==s2.top()) s2.pop(); //删除含有最小值的栈
        s1.pop();
    }
    
    int top() {
        return s1.top();
    }
    
    int getMin() {
        return s2.top();
    }
};


你可能感兴趣的:(Leetcode)