如何使用两个栈实现队列Java
作者:ERFishing 时间:2023-11-29 17:48:09
这篇文章主要介绍了如何使用两个栈实现队列Java,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
题目
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
题解
描述
栈的特性是先进后出,队列的特点是先进先出,当数字依次入栈1后,依次出栈1并且压入栈2后,然后再出栈的顺序与进入栈1的顺序是一致的。
因此,进入队列通过压入栈1实现,弹出队列通过弹出栈2的栈顶元素实现,在弹出元素时需要保证当前栈弹出元素的顺序和队列弹出元素的顺序一致,即栈1的元素应当全部压入到栈2中。
code
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
//直接入stack1栈
stack1.push(node);
}
public int pop() {
//若stack2为空
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
来源:https://www.cnblogs.com/ERFishing/p/11844387.html
标签:栈,实现,队列,java
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
android 修改launcher行数和列数的方法
2021-10-02 14:19:37
![](https://img.aspxhome.com/file/2023/1/139351_0s.png)
基于Unity3D实现仿真时钟详解
2021-05-24 15:11:34
![](https://img.aspxhome.com/file/2023/5/79065_0s.gif)
Android稳定性:可远程配置化的Looper兜底框架
2022-02-18 09:02:23
Android开发之自动朗读TTS用法分析
2021-08-21 22:31:00
Java制作智能拼图游戏原理及代码
2022-08-02 21:46:57
Unity实现识别图像中主体及其位置
2022-03-04 09:48:56
![](https://img.aspxhome.com/file/2023/9/113849_0s.png)
Java爬取网站源代码和链接代码实例
2023-06-25 01:11:29
![](https://img.aspxhome.com/file/2023/7/116217_0s.png)
RocketMQ之Consumer整体介绍启动源码分析
2022-06-04 03:53:31
![](https://img.aspxhome.com/file/2023/4/95944_0s.jpg)
Android EditText限制输入字数的方法
2021-11-20 18:39:39
浅谈c#中config.exe 引发的一些问题
2022-10-20 07:11:07
通过IDEA快速定位和排除依赖冲突问题
2021-06-07 02:01:16
![](https://img.aspxhome.com/file/2023/9/71919_0s.png)
C# 9.0 特性全面总结
2023-07-21 16:28:19
SpringBoot 集成 Druid过程解析
2023-02-25 12:07:59
![](https://img.aspxhome.com/file/2023/5/71655_0s.png)
Java实现TCP/IP协议的收发数据(服务端)代码实例
2023-08-11 08:44:51
![](https://img.aspxhome.com/file/2023/3/58063_0s.jpg)
java使用Feign实现声明式Restful风格调用
2023-01-22 08:18:05
Java ArrayDeque使用方法详解
2022-02-09 08:00:23
详解Java实现批量压缩图片裁剪压缩多种尺寸缩略图一键批量上传图片
2022-12-07 15:56:04
![](https://img.aspxhome.com/file/2023/1/77151_0s.png)
浅谈Java消息队列总结篇(ActiveMQ、RabbitMQ、ZeroMQ、Kafka)
2022-06-13 01:30:40
![](https://img.aspxhome.com/file/2023/8/60698_0s.jpg)
详解Mybatis动态sql
2023-09-16 15:41:38
![](https://img.aspxhome.com/file/2023/4/69924_0s.png)
Android使用Handler实现下载文件功能
2023-05-21 03:23:08
![](https://img.aspxhome.com/file/2023/3/137943_0s.gif)