Fork me on github

155 最小栈

import java.util.Stack;

class MinStack {

    //没有必要把所有元素都记录下来
    Stack<Integer> stack = new Stack<>();
    Stack<Integer> minStack = new Stack<>();

    /** initialize your data structure here. */
    public MinStack() {

    }

    public void push(int x) {
        stack.push(x);
        if(!minStack.isEmpty()){
            if(x <= minStack.peek())
                minStack.push(x);
        }
        else{
            minStack.push(x);
        }
    }

    public void pop() {
        if(!stack.isEmpty()){
            int temp = stack.pop();
            if(!minStack.isEmpty()){
                if(temp == minStack.peek()){
                    minStack.pop();
                }
            }
        }
    }

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

    public int getMin() {
            return minStack.peek();
    }
}

/**
 * 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.getMin();
 */
posted @ 2020-08-23 08:28  zjy4fun  阅读(77)  评论(0编辑  收藏  举报