当前位置:网站首页>用两个栈实现队列[两次先进后出便是先进先出]
用两个栈实现队列[两次先进后出便是先进先出]
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();
}
}
总结
参考文献
边栏推荐
- 【AI应用】NVIDIA Tesla V100-PCIE-32GB的详情参数
- Chapter 2 integrated mp
- Zero foundation self-study SQL course | complete collection of SQL basic functions
- Sécurité, économie de carburant et protection de l'environnement chameau
- ASP. Net warehouse purchase, sales and inventory ERP management system source code ERP applet source code
- C language character pointer and string initialization
- Applet referer
- 第 2 章 集成 MP
- 100 questions for an enterprise architect interview
- 安全省油環保 駱駝AGM啟停電池魅力十足
猜你喜欢
Applet referer
赛尔笔记|视频文本预训练简述
Teach you how to transplant tinyriscv to FPGA
ASP. Net warehouse purchase, sales and inventory ERP management system source code ERP applet source code
零基础自学SQL课程 | CASE函数
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!
Usage of vivado vio IP
[PCL self study: pclplotter] pclplotter draws data analysis chart
Golang - the difference between new and make
圖的存儲結構
随机推荐
Download versions such as typora 1.2.5
【AI应用】NVIDIA GeForce RTX 3060的详情参数
webService
Google Earth Engine(GEE) 03-矢量数据类型
[PCL self study: Segmentation3] PCL based point cloud segmentation: region growth segmentation
C language character pointer and string initialization
How to find Chinese documents corresponding to foreign documents?
单细胞数据清洗的这5个步骤你会做吗?
零基础自学SQL课程 | SQL基本函数大全
Started a natural language model bloom
Vivado FFT IP的使用说明
[AI application] detailed parameters of NVIDIA geforce RTX 1080ti
How to quote Chinese documents when writing a foreign language?
[PCL self study: pclvisualizer] point cloud visualization tool pclvisualizer
撰写外文时怎样引用中文文献?
安全省油环保 骆驼AGM启停电池魅力十足
搭建开源美观的数据库监控系统-Lepus
解决新版chrome跨域问题:cookie丢失以及samesite属性问题「建议收藏」
Instructions for vivado FFT IP
100 questions for an enterprise architect interview