1-155


class MinStack {
    
    private Stack<Integer> stackData;
    private Stack<Integer> stackMin;

    /** initialize your data structure here. */
    public MinStack() {
        this.stackData=new Stack<Integer>();
        this.stackMin=new Stack<Integer>();
    }
    
    public void push(int x) {
        if(this.stackMin.isEmpty()){
            this.stackMin.push(x);
        }else if(x<=this.getMin()){
            this.stackMin.push(x);
        }
        this.stackData.push(x);
    }
    
    public void pop() {
        if(this.stackData.isEmpty()){
            throw new RuntimeException("Your stack is empty");
        }
        int value=this.stackData.pop();
        if(value==this.getMin()){
            this.stackMin.pop();
        }
    }
    
    public int top() {
        if(this.stackData.isEmpty()){
            throw new RuntimeException("Your stack is empty");
        }
        return this.stackData.peek();
    }
    
    public int getMin() {
        if(this.stackMin.isEmpty()){
            throw new RuntimeException("Your stack is empty");
        }
        return this.stackMin.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();
 */

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM