【数据结构 - 队列】:力扣题:用队列实现栈

问题描述

225. 用队列实现栈 - 力扣(LeetCode)

题目分析

 栈:先进后出

队列:先进先出

一个队列肯定是实现不了栈的,要两个队列来模拟出先进后出

 假设

 如果是栈的情况下

 先出的应该是34

但是现在是队列,出的话我们只能先出12

那应该怎么做把12出出来放到第二个队列,23出出来放到第二个队列

那么队列1就剩了一个元素,直接出出去就可以了,就相当于栈出去的第一个元素34

现在假设要放45这个元素

记住一点,每次入数据的时候都入到那个不为空的队列

现在我们要出45,同理,先把12和23入到队列1,然后出45就可以了

 1.入栈的时候,入到不为空的队列,刚开始都为空指定入到一个队列

2.出栈的时候,找到不为空的队列,出size-1个元素到另一个队列,剩下的这个元素就是出栈的元素

完整代码

class MyStack {
    private Queue<Integer> queue; 
    private Queue<Integer> queue1; 


    public MyStack() {
        queue = new LinkedList<>();
        queue1 = new LinkedList<>();

    }
    
    public void push(int x) {
        if(!queue.isEmpty()){
            queue.offer(x);
        }else if(!queue1.isEmpty()){
            queue1.offer(x);
        }else{
            queue1.offer(x);
        }

    }
    
    public int pop() {

        if(empty()) return -1;

        if(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0; i < size-1; i++){
                int val = queue.poll();
                queue1.offer(val);
            }
            return queue.poll();
        }
        if(!queue1.isEmpty()){
            int size = queue1.size();
            for(int i = 0; i < size-1; i++){
                int val = queue1.poll();
                queue.offer(val);
            }
            return queue1.poll();
        }
        return -1;

    }
    //得到队头元素
    public int top() {
        if(!queue.isEmpty()){
             int val = -1;
             int size = queue.size();
            for(int i = 0; i < size; i++){
                val = queue.poll();
                queue1.offer(val);
            }
            return val;
        }
        if(!queue1.isEmpty()){
             int val = -1;
             int size = queue1.size();
            for(int i = 0; i < size; i++){
                val = queue1.poll();
                queue.offer(val);
            }
            return val;
        }
        return -1;

    }
    
    public boolean empty() {
        return queue1.isEmpty() && queue.isEmpty();

    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

K稳重

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值