当前位置:网站首页>剑指 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(); */
}
}
边栏推荐
- Programmers' experience of delivering takeout
- Heap sort summary
- 二十六、文件系统API(设备在应用间的共享;目录和文件API)
- 使用命令符关闭笔记本自带键盘命令
- TF-A中的工具介绍
- [binary search] 34 Find the first and last positions of elements in a sorted array
- On-off and on-off of quality system construction
- Drawing dynamic 3D circle with pure C language
- [turn to] MySQL operation practice (III): table connection
- sync. Interpretation of mutex source code
猜你喜欢
SAP-修改系统表数据的方法
Remote upgrade afraid of cutting beard? Explain FOTA safety upgrade in detail
sync. Interpretation of mutex source code
Embedded database development programming (zero)
Yolov5 ajouter un mécanisme d'attention
The present is a gift from heaven -- a film review of the journey of the soul
Introduction to tools in TF-A
SAP method of modifying system table data
Web APIs DOM node
小程序直播+电商,想做新零售电商就用它吧!
随机推荐
Research on the value of background repeat of background tiling
Binary search basis
Es module and commonjs learning notes
【ES实战】ES上的native realm安全方式使用
Talking about JVM (frequent interview)
[interval problem] 435 Non overlapping interval
Pointnet++学习
Haut OJ 1350: choice sends candy
[to be continued] [depth first search] 547 Number of provinces
C语言杂谈1
SDEI初探-透过事务看本质
Introduction to tools in TF-A
Yolov5 adds attention mechanism
[es practice] use the native realm security mode on es
Grail layout and double wing layout
MySQL数据库(一)
二十六、文件系统API(设备在应用间的共享;目录和文件API)
Use of room database
Collapse of adjacent vertical outer margins
Csp-j-2020-excellent split multiple solutions