当前位置:网站首页>Using two stacks to implement queues [two first in first out is first in first out]
Using two stacks to implement queues [two first in first out is first in first out]
2022-06-27 23:58:00 【REN_ Linsen】
Queues are implemented with two stacks
Preface
The queue is characterized by first in, first out , The stack is characterized by last in, first out , If LIFO and then new stack , That's first in, first out .
One 、 Queues are implemented with two stacks

Two 、 Two in and out to get the queue
package everyday.simple;
import java.util.Stack;
// Two stacks realize the first in, first out of queues .
public class CQueue {
/* target: Use a LIFO stack Implement a first in first out queue . The way in and out of the stack and the way in the queue just want to change , If you put the elements in the stack on another stack , Then the order of this stack , Namely The first element enters the stack 1 The order of . */
Stack<Integer> in, out;
public CQueue() {
in = new Stack<>();
out = new Stack<>();
}
public void appendTail(int value) {
in.push(value);
}
public int deleteHead() {
// if in return, First of all , Make a good arrangement for the location of conditional visits , Try not to nest if and if else; second , Combine blocks of code that do the same thing under different conditions .
// Both stacks are empty
if (out.isEmpty() && in.isEmpty()) return -1;
// in There are elements in the stack , hold in All stack elements are taken out
if (out.isEmpty()) while (!in.isEmpty()) out.push(in.pop());
// out There are elements in the stack at this time , Just get it out of the stack .
return out.pop();
}
}
summary
reference
边栏推荐
- 刚开始看英文文献,想问一下各位,最初应该怎么看进去?
- vivado 如何添加时序约束
- 系统学习+主动探索,是最舒适的入门学习方式!
- Elk in Windows Environment - logstash+mysql (4)
- MySQL character set
- Zero foundation self-study SQL course | case function
- Safe, fuel-efficient and environment-friendly camel AGM start stop battery is full of charm
- C WinForm reads the resources picture
- 【PCL自学:PCLVisualizer】点云可视化工具PCLVisualizer
- mysql读写分离配置
猜你喜欢
随机推荐
圖的存儲結構
golang使用mongo-driver操作——查(基础)
[PCL self study: segmentation4] point cloud segmentation based on Min cut
Golang - the difference between new and make
【tinyriscv verilator】分支移植到正点原子达芬奇开发板
获取基因有效长度的N种方法
手把手教你移植 tinyriscv 到FPGA上
Build an open source and beautiful database monitoring system -lepus
Applet referer
[digital ic/fpga] detect the position of the last matching sequence
虽然TCGA数据库有33种癌症
halcon之区域:多种区域(Region)特征(6)
ASP.NET仓库进销存ERP管理系统源码 ERP小程序源码
搭建开源美观的数据库监控系统-Lepus
Halcon's region: features of multiple regions (6)
计数质数[枚举 -> 空间换时间]
文献综述如何挑选文献进行阅读,比如我的检索结果有200多篇根本看不完,如何进行文献挑选呢?...
How to find Chinese documents corresponding to foreign documents?
Are the registered accounts of the top ten securities companies safe and risky?
Webserver flow chart -- understand the calling relationship between webserver modules









![[sword finger offer] 47 Maximum value of gifts](/img/bc/1aff1223b1672c4089151dc56c4d4e.png)