LeetCode—剑指Offer:用两个栈实现队列(暴力)

用两个栈实现队列(简单)

2020年8月11日

题目来源:力扣

在这里插入图片描述

解题

  • 暴力
    每次传数就传到st1,要删除值就把st1的值传到st2,这样就会反转数值,把最先进栈的放到最上面,可以输出,做删除操作后再把st2传回st1。这样太费时了
class CQueue {
    private Stack<Integer> st1;
    private Stack<Integer> st2;
    public CQueue() {
        st1=new Stack<Integer>();
        st2=new Stack<Integer>();
    }
    
    public void appendTail(int value) {
        st1.push(value);
    }
    
    public int deleteHead() {
        int delnum=-1;
        if(!st1.empty()){
            while(!st1.empty()){
                st2.push(st1.pop());
            }
            delnum=st2.pop();
            while(!st2.empty()){
                st1.push(st2.pop());
            }
        }
        return delnum;
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */

在这里插入图片描述

  • 暴力plus
    专门把st2作为输出专用,当st2为空的时候再把st1的所有数出栈压进去,否则就直接用st2里的值
class CQueue {
    private Stack<Integer> st1;
    private Stack<Integer> st2;
    public CQueue() {
        st1=new Stack<Integer>();
        st2=new Stack<Integer>();
    }
    
    public void appendTail(int value) {
        st1.push(value);
    }
    
    public int deleteHead() {
        int delnum=-1;
        //当st2为空,就把st1出栈放进去
        if(st2.empty()){
            while(!st1.empty()){
                st2.push(st1.pop());
            }
        }
        if(!st2.empty()){
            delnum=st2.pop();
        }
        return delnum;
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值