[LeetCode]225. 用队列实现栈(java实现)

1. 题目

在这里插入图片描述

2. 读题(需要重点注意的东西)

队列的特性—先进先出
思路:由于队列的先进先出特性,因此与用栈实现队列的思路不同,用队列来实现栈需要思考如何能将先入先出,转化为先入后出。

3. 解法

class MyStack {
    private Queue<Integer> queueIn;//输入队列
    private Queue<Integer> queueOut;//输出队列
    
    public MyStack() {
        queueIn = new LinkedList<>();
        queueOut = new LinkedList<>();
    }
    
    public void push(int x) {
        queueIn.offer(x);
        //接下来四句代码实现了由先入先出转换为先入后出,详见后文总结
        while(!queueOut.isEmpty()){queueIn.offer(queueOut.poll());}
        Queue temp = queueIn;
        queueIn = queueOut;
        queueOut = temp;
    }
    
    public int pop() {
        return queueOut.poll();
    }
   
    public int top() {
        return queueOut.peek();
    }
    
    public boolean empty() {
        return queueOut.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

4. 可能有帮助的前置习题

[LeetCode]232. 用栈实现队列(java实现)

5. 所用到的数据结构与算法思想

6. 总结

public void push(int x) {
    queueIn.offer(x);
    //接下来四句代码实现了由先入先出转换为先入后出,详见后文总结
    while(!queueOut.isEmpty()){queueIn.offer(queueOut.poll());}
    Queue temp = queueIn;
    queueIn = queueOut;
    queueOut = temp;
}

对上文代码的理解: 输入 1 、2两个元素;

  1. 当输入x = 1时:(详细的队列信息见注释)
// 输入前queueIn = [ ] ,queueOut = [ ]
queueIn.offer(x); //queueIn = [ 1 ]
 while(!queueOut.isEmpty()){queueIn.offer(queueOut.poll());} // queueIn = [ 1 ],queueOut = [ ]
Queue temp = queueIn; // queueIn = [ 1 ],queueOut = [ ],temp = [ 1 ]
queueIn = queueOut; // queueIn = [  ],queueOut = [  ],temp = [ 1 ]
queueOut = temp;// queueIn = [  ],queueOut = [ 1 ],temp = [ 1 ]
  1. 当输入x = 2时:(详细的队列信息见注释)
// 输入前queueIn = [ ] ,queueOut = [ 1 ]
queueIn.offer(x); //queueIn = [ 2 ]
 while(!queueOut.isEmpty()){queueIn.offer(queueOut.poll());} // queueIn = [ 2, 1 ],queueOut = [  ] (queueOut已经poll出元素了,所以当执行完当前操作时,queueOut为空)
Queue temp = queueIn; // queueIn = [ 2, 1 ],queueOut = [  ],temp = [ 2, 1 ]
queueIn = queueOut; // queueIn = [  ],queueOut = [  ],temp = [ 2, 1 ]
queueOut = temp;// queueIn = [  ],queueOut = [ 2, 1 ],temp = [ 2, 1 ]

因此,在执行完上述五行代码后,能够实现由先入先出,变为先入后出;并且在每次输入元素时,queueIn都为空。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Cloudeeeee

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

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

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

打赏作者

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

抵扣说明:

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

余额充值