当前位置:网站首页>由两个栈组成的队列
由两个栈组成的队列
2022-06-28 13:46:00 【华为云】
由两个栈组成的队列
【题目】
编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)。
【思路】
前景知识:栈,先进后出;队列,先进先出
两个栈实现队列,用两个栈就是为了让栈中的数据反转一次,数据如a栈,把a栈的数据都pop出来push到b栈,这样a栈栈底的东西就会到b栈的栈顶了,有两个前提:
- a栈往b栈压数据时,必须把a栈中数据全部压入b栈
- 只有b栈为空,才能往b栈压入数据
【代码】
package keafmd.accumulate.codeinterviewguide.twostacksformaqueue;import java.util.Stack;/** * Keafmd * * @ClassName: MyStack1 * @Description: 两个栈实现的队列 add、poll、peek * @author: 牛哄哄的柯南 * @date: 2022-06-21 17:38 */public class TwoStacksQueue { Stack<Integer> stackA; Stack<Integer> stackB; public TwoStacksQueue(){ stackA = new Stack<>(); stackB = new Stack<>(); } //转移 a栈的数据全部倒入b栈 public void transfer(){ if(stackB.isEmpty()){ while(!stackA.isEmpty()){ stackB.push(stackA.pop()); } } } public void add(Integer val){ stackA.push(val); transfer(); } public Integer poll(){ if(stackA.isEmpty()&&stackB.isEmpty()){ throw new RuntimeException("Queue is empty!"); } transfer(); return stackB.pop(); } public Integer peek(){ if(stackA.isEmpty()&&stackB.isEmpty()){ throw new RuntimeException("Queue is empty!"); } transfer(); return stackB.peek(); }}
边栏推荐
- How to design data visualization platform
- Mobile web training day-2
- Professional English calendar questions
- NFT digital collection system development (3D modeling economic model development case)
- SPI接口简介-Piyu Dhaker
- My hematemesis collection integrates script teaching from various classic shell books. As Xiaobai, come quickly
- Hubble数据库x某股份制商业银行:冠字号码管理系统升级,让每一张人民币都有 “身份证”
- How to set auto format after saving code in vscade
- 2.01 backpack problem
- (原创)【MAUI】一步一步实现“悬浮操作按钮”(FAB,Floating Action Button)
猜你喜欢
Latest summary! 30 provinces announce 2022 college entrance examination scores
If a programmer goes to prison, will he be assigned to write code?
设计人工智能产品:技术可能性、用户合意性、商业可行性
Make an ink screen electronic clock, cool!
Kubernetes 深入理解Kubernetes(二) 声明组织对象
Inftnews | technology giants accelerate their march into Web3 and metauniverse
Nature子刊 | 绘制植物叶际菌群互作图谱以建立基因型表型关系
Kubernetes 深入理解kubernetes(一)
From PDB source code to frame frame object
Pytorch Foundation
随机推荐
Pytorch Foundation
StackOverflow 2022数据库年度调查
N皇后问题
木兰开放作品许可证1.0面向社会公开征求意见
Jupyter notebook中添加虚拟环境
Unit test ci/cd
go数组与切片,[]byte转string[通俗易懂]
Nature子刊 | 绘制植物叶际菌群互作图谱以建立基因型表型关系
3、项目的整体UI架构
Why do more and more users give up swagger and choose apifox
中国广电5G套餐来了,比三大运营商低,却没预期那么低
Yii2 connects to websocket service to realize that the server actively pushes messages to the client
如何备份mysql_史上最全的MYSQL备份方法
Explanation of sprintf function in C language
单元测试 CI/CD
How to design data visualization platform
《畅玩NAS》家庭 NAS 服务器搭建方案「建议收藏」
GPS数据格式的分析与处理[通俗易懂]
[机缘参悟-32]:鬼谷子-抵巇[xī]篇-面对危险与问题的五种态度
CVPR再起争议:IBM中稿论文被指照搬自己承办竞赛第二名的idea