其他分享
首页 > 其他分享> > 1-1 带有getmin功能的栈

1-1 带有getmin功能的栈

作者:互联网

题目描述

解题尝试

解题方法1

class stack{
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    stack(){
        this.stack1 = new Stack<>();
        this.stack2 = new Stack<>();
    }
    public void push(int x){
        this.stack1.push(x);
        if(this.stack2.empty() || x<=this.stack2.peek()){
           this.stack2.push(x);
        }
    }
    public Integer pop(){
        if(this.stack1.empty()){
            throw new RuntimeException("stack empty");
        }
       int e = this.stack1.pop();
       if(e == this.stack2.peek()){
           this.stack2.pop();
       }
       return e;
    }
    public Integer getmin(){
        if(this.stack2.empty()){
            throw new RuntimeException("stack empty");
        }
        return this.stack2.peek();
    }
}

解题方法2

class stack{
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    stack(){
        this.stack1 = new Stack<>();
        this.stack2 = new Stack<>();
    }
    public void push(int x){
        this.stack1.push(x);
        if(this.stack2.empty() || x<=this.stack2.peek()){
           this.stack2.push(x);
        }
        if(x>this.stack2.peek()){
            this.stack2.push(this.stack2.peek());
        }
    }
    public Integer pop(){
        if(this.stack1.empty()){
            throw new RuntimeException("stack empty");
        }
        int e = this.stack1.pop();
        this.stack2.pop();
       return e;
    }
    public Integer getmin(){
        if(this.stack2.empty()){
            throw new RuntimeException("stack empty");
        }
        return this.stack2.peek();
    }
}
zuiziyoudexiao 发布了92 篇原创文章 · 获赞 61 · 访问量 17万+ 私信 关注

标签:功能,出栈,元素,栈顶,getmin,带有,stack2,Stack,stack1
来源: https://blog.csdn.net/zuiziyoudexiao/article/details/104572751