数据结构-队列与栈之间的转换
队列:火车过隧道。。。火车头先进隧道先出隧道、、、先进先出
栈:桶里倒水再倒出。。。先进后出。。。
两个堆栈实现队列与两个队列实现堆栈
package Test2016.test; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class Test20160329 { public static void main(String[] args) { /** * @desc 两个堆栈实现队列 * @idea 堆栈:先进后出,队列:先进先出 * */ MyQueue myQueue = new MyQueue(); System.out.println("入队列顺序:"); for (int i = 1; i <= 10; i++) { System.out.print(i + " "); myQueue.push_q(i); } System.out.println("\n用堆栈实现【队列】弹出:"); for (int i = 0; i < 10; i++) { System.out.print(myQueue.pop_q() + " "); } System.out.println("\n######################"); /** * @desc 两个队列实现堆栈 * @idea 堆栈:先进后出,队列:先进先出 * */ MyStack myStack = new MyStack(); System.out.println("入堆栈顺序:"); for (int i = 1; i <= 10; i++) { System.out.print(i + " "); myStack.push_s(i); } System.out.println("\n用队列实现【堆栈】弹出:"); for (int i = 0; i < 10; i++) { System.out.print(myStack.pop_s() + " "); } } } class MyQueue { private Stack<Integer> s1 = null; private Stack<Integer> s2 = null; public MyQueue() { s1 = new Stack<Integer>(); s2 = new Stack<Integer>(); } public Integer push_q(Integer p) { s1.push(p); return p; } public Integer pop_q() { Integer res = null; if (!s2.isEmpty()) { res = s2.pop(); } else { while (!s1.isEmpty()) { res = s1.pop(); s2.push(res); } if (!s2.isEmpty()) { res = s2.pop(); } } return res; } } class MyStack { private Queue<Integer> q1 = null; private Queue<Integer> q2 = null; public MyStack() { q1 = new LinkedList<Integer>(); q2 = new LinkedList<Integer>(); } public Integer push_s(Integer p) { q1.add(p); return p; } public Integer pop_s() { Integer res = null; boolean flag = true; //标识变量 if (q2.size() > 0 && flag == true) { flag = false; while (q2.size() > 0) { if (q2.size() > 0) { res = q2.remove(); q1.add(res); } } q1.remove(res); } else if (q1.size() > 0 && flag == true) { while (q1.size() > 0) { if (q1.size() > 0) { res = q1.remove(); q2.add(res); } } q2.remove(res); } return res; } }
程序运行输出:
入队列顺序: 1 2 3 4 5 6 7 8 9 10 用堆栈实现【队列】弹出: 1 2 3 4 5 6 7 8 9 10 ###################### 入堆栈顺序: 1 2 3 4 5 6 7 8 9 10 用队列实现【堆栈】弹出: 10 9 8 7 6 5 4 3 2 1
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?