首页 > 其他 > 详细

1-155

时间:2018-09-26 11:26:52      阅读:180      评论:0      收藏:0      [点我收藏+]
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();
 */

 

1-155

原文:https://www.cnblogs.com/chanaichao/p/9705811.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!