当前位置:网站首页>剑指 Offer 09. 用两个栈实现队列
剑指 Offer 09. 用两个栈实现队列
2022-07-05 05:26:00 【ThE wAlkIng D】
题目描述

问题解析(本题使用滑动窗口+HashMap)
1.首先定义两个栈s1,s2,s1的栈顶作为队尾,s2的栈顶作为队投
2.删除操作首先判断s2是否为空 如果不为空,把栈顶元素弹出就是头元素 如果为空,将s1所有元素弹出入栈到s2
3.s2为空返回-1,不为空返回栈顶元素
代码实例
class CQueue {
Stack<Integer> s1 = new Stack<>(); // s1的栈顶是队尾,新加入的元素在该栈栈顶
Stack<Integer> s2 = new Stack<>(); // s2的栈顶是队头
public CQueue() {
}
public void appendTail(int value) {
s1.push(value); // 压入栈s1
}
public int deleteHead() {
if(!s2.isEmpty()) {
// 若s2不空,直接弹出栈顶元素即为队头元素
return s2.pop();
}
// s2为空,将s1所有元素弹出,入栈到s2
while(!s1.isEmpty()) {
s2.push(s1.pop());
}
return s2.isEmpty() ? -1 : s2.pop(); // s2为空,返回-1;s2不为空返回栈顶元素
}
}
/** * Your CQueue object will be instantiated and called as such: * CQueue obj = new CQueue(); * obj.appendTail(value); * int param_2 = obj.deleteHead(); */
}
}
边栏推荐
- Haut OJ 1241: League activities of class XXX
- Warning using room database: schema export directory is not provided to the annotation processor so we cannot export
- Research on the value of background repeat of background tiling
- 读者写者模型
- FVP和Juno平台的Memory Layout介绍
- Haut OJ 1243: simple mathematical problems
- 2022上半年全国教师资格证下
- Applet live + e-commerce, if you want to be a new retail e-commerce, use it!
- Optimization scheme of win10 virtual machine cluster
- sync. Interpretation of mutex source code
猜你喜欢
随机推荐
软件测试 -- 0 序
Introduction to tools in TF-A
The present is a gift from heaven -- a film review of the journey of the soul
Research on the value of background repeat of background tiling
Remote upgrade afraid of cutting beard? Explain FOTA safety upgrade in detail
room数据库的使用
PMP candidates, please check the precautions for PMP examination in July
质量体系建设之路的分分合合
二十六、文件系统API(设备在应用间的共享;目录和文件API)
Software test -- 0 sequence
Zzulioj 1673: b: clever characters???
Bubble sort summary
Haut OJ 1347: addition of choice -- high progress addition
Solon Auth 认证框架使用演示(更简单的认证框架)
GBase数据库助力湾区数字金融发展
2022上半年全国教师资格证下
Animation scoring data analysis and visualization and it industry recruitment data analysis and visualization
Programmers' experience of delivering takeout
Add level control and logger level control of Solon logging plug-in
[allocation problem] 135 Distribute candy
![[轉]: OSGI規範 深入淺出](/img/54/d73a8d3e375dfe430c2eca39617b9c.png)




![[转]MySQL操作实战(三):表联结](/img/70/20bf9b379ce58761bae9955982a158.png)



