当前位置:网站首页>用两个栈实现队列[两次先进后出便是先进先出]
用两个栈实现队列[两次先进后出便是先进先出]
2022-06-27 21:24:00 【REN_林森】
用两个栈实现队列
前言
队列的特点是先进先出,栈的特点是后进先出,如果后进先出再入新栈,那就是先进先出。
一、用两个栈实现队列

二、两次先进后出得到队列
package everyday.simple;
import java.util.Stack;
// 两个栈实现队列的先进先出。
public class CQueue {
/* target:用后进先出的栈 实现先进先出的队列。 栈的进出方式和队列的方式刚好想反,如果把栈中的元素有入栈另一个栈,则这个栈的出栈顺序,就是 最开始元素进入栈1的顺序。 */
Stack<Integer> in, out;
public CQueue() {
in = new Stack<>();
out = new Stack<>();
}
public void appendTail(int value) {
in.push(value);
}
public int deleteHead() {
// if中存在return,第一,就好好编排条件的拜访位置,尽量没有嵌套if和if else;第二,把不同条件做相同操作的代码块合并在一起。
// 两栈都为空
if (out.isEmpty() && in.isEmpty()) return -1;
// in栈中有元素,把in栈元素全部拿到out
if (out.isEmpty()) while (!in.isEmpty()) out.push(in.pop());
// out栈中此时有元素,让其出栈即可。
return out.pop();
}
}
总结
参考文献
边栏推荐
- Storage structure of graph
- 【剑指Offer】48. 最长不含重复字符的子字符串
- ClickOnce error deploying ClickOnce application - the reference in the manifest does not match the identity of the downloaded assembly
- 零基础自学SQL课程 | SQL基本函数大全
- 赛尔笔记|视频文本预训练简述
- [digital ic/fpga] detect the position of the last matching sequence
- golang - new和make的区别
- Golang uses Mongo driver operation - query (basic)
- How to set the enterprise wechat group robots to send messages regularly?
- Practice torch FX: pytorch based model optimization quantization artifact
猜你喜欢

Structure de stockage des graphiques

EXCEL 打印设置公共表头

Applet referer

C WinForm reads the resources picture

Instructions for vivado FFT IP

【PCL自学:PCLPlotter】PCLPlotter绘制数据分析图

How to quote Chinese documents when writing a foreign language?
![[PCL self study: segmentation4] point cloud segmentation based on Min cut](/img/af/a6c5abf357c1db0718df505499df70.png)
[PCL self study: segmentation4] point cloud segmentation based on Min cut
![[microservices sentinel] sentinel data persistence](/img/9f/2767945db99761bb35e2bb5434b44d.png)
[microservices sentinel] sentinel data persistence

vmware虚拟机桥接连通
随机推荐
C language character pointer and string initialization
十大券商注册账户安全吗,会有风险吗?
UESTC (shenhengtao team) & JD AI (Mei Tao team) proposed a structured dual stream attention network for video Q & A, with performance SOTA! Better than the method based on dual video representation!
零基础自学SQL课程 | CASE函数
mysql读写分离配置
Course strategy sharing plan of Zhejiang University
Grab those duplicate genes
Webserver flow chart -- understand the calling relationship between webserver modules
c语言-日期格式化[通俗易懂]
One step forward is excellent, one step backward is ignorant
【AI应用】Jetson Xavier NX的详情参数
[AI application] detailed parameters of NVIDIA geforce RTX 1080ti
MSP430F5529 单片机 读取 GY-906 红外温度传感器
Feign implements path escape through custom annotations
Super outline exercises
After a period of silence, I came out again~
【AI应用】NVIDIA Tesla V100S-PCIE-32GB的详情参数
Stream + Nacos
Cornernet understands from simple to profound
Instructions for vivado FFT IP