Java-刷题-栈

题目链接:https://leetcode-cn.com/problems/min-stack/

使用语言:Java

class MinStack {
    Stack st = new Stack();
    Stack st2 = new Stack();
    /** initialize your data structure here. */
    public MinStack() {
        
    }
    
    public void push(int x) {
        st.push(x);
        if(st2.isEmpty()||x<=st2.peek()){
            st2.push(x);
        }
    }
    
    public void pop() {
        int x = st.pop();
        if(!st2.isEmpty()&&st2.peek()==x)st2.pop();
        
    }
    
    public int top() {
        return st.peek();
    }
    
    public int getMin() {
        if(!st2.isEmpty()){
            return st2.peek();
        }else if(!st.isEmpty()){
            return st.peek();
        }else{
            return 0;
        }
    }
}

你可能感兴趣的:(Java-刷题-栈)