当前位置:网站首页>剑指offer09--用两个栈实现队列
剑指offer09--用两个栈实现队列
2022-06-09 09:12:00 【星域_03zhan】
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
分析:
这里需要两个栈来实现队列的功能。
栈遵循先进后出的原则,队列遵循先进先出的原则。
用第一个栈来存入元素,这时最先进入的元素在栈底,然后将第一个栈中的元素移动到新栈中,这时最先进入的元素就在栈顶了,然后用第二个栈出栈时,整个执行的顺序就变成了先进先出。
class CQueue{
Stack<Integer> inputStack; //第一个栈
Stack<Integer> outputStack;//第二个栈
public CQueue{
inputStack=new Stack();
outputStack=new Stack();
}
public int appendTail(int value){
inputStack.push(value);//push():向栈顶添加元素
}
public void deleteHead(){
if(!outputStack.isEmpty()){
return outputStack.pop(); //弹出元素
}else if(!inputStack.isEmpty()){
while(!inputStack.isEmpty()){
outputStack.push(inputStack.pop);
}
}
return outputStack.isEmpty() ? -1 : outputStack.pop();
}
}
边栏推荐
- 面试官:如何秒开视频?什么是秒开视频?
- How to draw a picture gracefully
- Creation of menu for wechat applet development
- [texstudio] [2] general picture and table presentation
- 2022-2028 global linear LED lighting industry research and trend analysis report
- 根据投影坐标裁剪影像中的目标区域(附有完整代码)
- LeetCode_栈_困难_394. 字符串解码
- 【图机器学习】启发式链路预测方法
- Database problems MySQL
- Have fun | sofaark source code analysis activity
猜你喜欢

初级指针~带你入门指针

Understand the graph database neo4j (II)

了解图数据库neo4j(一)

Understand the graph database neo4j (III)
![[matlab] [digital simulation] [1] linprog solving linear programming, standard type](/img/e2/584ff7809bcad613b157a6a17d53db.png)
[matlab] [digital simulation] [1] linprog solving linear programming, standard type

如今的Android 开发都怎么了?我问的面试题有这么难吗?

How do you view the multi runtime architecture of dapr and layotto?

Kusionstack has a sense of open source | it took two years to break the dilemma of "separating lines like mountains"

【计算机网络-19】计算机网络面试题

数据科学的道德与法规知识
随机推荐
C language pointer
【线性代数】理解正定矩阵和半正定矩阵
Esp32 learning notes [WiFi network] - 01ap & sta
MySQL basic functions
解决apscheduler报错:Run time of job …… next run at: ……)” was missed by
2022-2028 global linear LED lighting industry research and trend analysis report
Interviewer: how to open a video? What is second on video?
微信小程序--嘟嘟会议--会议发布和我的会议查看
LeetCode_模拟_中等_621. 任务调度器
dotnet core 也能协调分布式事务啦!
Sofa weekly | kusion open source, QA this week, contributor this week
Dotnet core can also coordinate distributed transactions!
Qt development -- compilation of serial port assistant
Judge whether it is JSON or file stream
初级指针~带你入门指针
In depth analysis: what is the prospect of doing software testing at the age of 25?
判断是Json还是文件流
xml转Map(递归调用读取XML全部节点内容) readXml 读取xml
[redis learning 11] data persistence of distributed cache, master-slave cluster
【推荐系统】基于用户的协同过滤