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

class MinStack {
    Stack<Integer> data;
    Stack<Integer> helper;
    /** initialize your data structure here. */
    public MinStack() {
        data = new Stack<Integer>();
        helper = new Stack<Integer>();
    }
    
    public void push(int x) {
        data.push(x);
        if(helper.size() == 0)
        {
            helper.push(x);
        }
        else
        {
            if(helper.peek() >= x)
            {
                helper.push(x);
            }
        }
    }
    
    public void pop() {
        int ans = data.pop();
        if(ans == helper.peek())
        {
            helper.pop();
        }

    }
    
    public int top() {
        return data.peek();
    }
    
    public int min() {
        return helper.peek();
    }
}
原文地址:https://www.cnblogs.com/swqblog/p/13288766.html