双栈实现队列(改进版)

两个栈实现队列(改良版)

原理分析

  • 栈:先进后出;队列:先进先出
  • 现在初始化两个栈 stack1stack2,一个进,一个出
  • 进队:直接压入 stack1
  • 出队:最开始,stack2 里面是没有东西的,那么这时候就把 stack1 里面的所有元素依次 pop 出,并 pushstack1; 全部转移之后,处于 stack2 栈顶的就是最早进入 stack1 的元素,这时,对 stack2 进行 pop, 出去的就是最早进入队列(双栈)的元素;第一次之后,stack2 中已经有元素,此后每次 pop 只需要判断一下 stack2 是否为空,非空直接 pop ,为空则再转移一下
  • 先进先出,完美实现
  • 细节的判断看代码

代码

class SimulatedQueue{

    private Stack<Integer> stack1 = new Stack<>();
    private Stack<Integer> stack2 = new Stack<>();
    public int size = 0;

    //Stack1 as input collection
    public void insert(Integer i){
        stack1.push(i);
        size ++;
    }

    public Integer pop(){
        if(size <= 0) return null;
        //Transfer all the elements from stack1 to stack2, then all the sequence are reversed.
        //So if we pop stack2 now, the first element pushed to stack1 are now popped first.
        //That's "first in , first out" just like queue
        if(stack2.size() <= 0){
            int size1 = stack1.size();
            for(int i = 0; i < size1; i ++){
                stack2.push(stack1.pop());
            }
        }
        size --;
        return stack2.pop();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值