当前位置:网站首页>剑指 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(); */
}
}
边栏推荐
- 2022年上半年国家教师资格证考试
- 26、 File system API (device sharing between applications; directory and file API)
- [转]:Apache Felix Framework配置属性
- Reverse one-way linked list of interview questions
- [to be continued] [depth first search] 547 Number of provinces
- kubeadm系列-01-preflight究竟有多少check
- 第六章 数据流建模—课后习题
- [turn]: OSGi specification in simple terms
- 2022上半年全国教师资格证下
- Drawing dynamic 3D circle with pure C language
猜你喜欢
Using HashMap to realize simple cache
[merge array] 88 merge two ordered arrays
[depth first search] 695 Maximum area of the island
Support multi-mode polymorphic gbase 8C database continuous innovation and heavy upgrade
利用HashMap实现简单缓存
支持多模多态 GBase 8c数据库持续创新重磅升级
To be continued] [UE4 notes] L4 object editing
Embedded database development programming (VI) -- C API
Introduction to tools in TF-A
Reader writer model
随机推荐
Acwing 4300. Two operations
使用Electron开发桌面应用
发现一个很好的 Solon 框架试手的教学视频(Solon,轻量级应用开发框架)
What is the agile proportion of PMP Exam? Dispel doubts
Es module and commonjs learning notes -- ESM and CJS used in nodejs
TF-A中的工具介绍
挂起等待锁 vs 自旋锁(两者的使用场合)
第六章 数据流建模—课后习题
Research on the value of background repeat of background tiling
Heap sort summary
YOLOv5添加注意力機制
lxml.etree.XMLSyntaxError: Opening and ending tag mismatch: meta line 6 and head, line 8, column 8
YOLOv5-Shufflenetv2
Gbase database helps the development of digital finance in the Bay Area
64 horses, 8 tracks, how many times does it take to find the fastest 4 horses at least
二十六、文件系统API(设备在应用间的共享;目录和文件API)
C language Essay 1
Magnifying glass effect
[to be continued] I believe that everyone has the right to choose their own way of life - written in front of the art column
[转]MySQL操作实战(一):关键字 & 函数