当前位置:网站首页>Sword finger offer 09 Implementing queues with two stacks
Sword finger offer 09 Implementing queues with two stacks
2022-07-05 05:28:00 【ThE wAlkIng D】
Title Description

Problem analysis ( This question uses a sliding window +HashMap)
1. First define two stacks s1,s2,s1 The top of the stack is the tail of the team ,s2 The top of the stack as a team cast
2. To delete, first judge s2 Is it empty If it's not empty , Popping the top element of the stack is the header element If it is empty , take s1 All elements pop into the stack s2
3.s2 Empty return -1, If it is not empty, return the top of stack element
Code instance
class CQueue {
Stack<Integer> s1 = new Stack<>(); // s1 The top of the stack is the tail of the team , The newly added element is at the top of the stack
Stack<Integer> s2 = new Stack<>(); // s2 At the top of the stack is the head of the team
public CQueue() {
}
public void appendTail(int value) {
s1.push(value); // Push to stack s1
}
public int deleteHead() {
if(!s2.isEmpty()) {
// if s2 Not empty , Directly pop up the top element of the stack, that is, the team head element
return s2.pop();
}
// s2 It's empty , take s1 All elements pop up , Stack to s2
while(!s1.isEmpty()) {
s2.push(s1.pop());
}
return s2.isEmpty() ? -1 : s2.pop(); // s2 It's empty , return -1;s2 If it is not empty, return the top of stack element
}
}
/** * Your CQueue object will be instantiated and called as such: * CQueue obj = new CQueue(); * obj.appendTail(value); * int param_2 = obj.deleteHead(); */
}
}
边栏推荐
- Under the national teacher qualification certificate in the first half of 2022
- Zheng Qing 21 ACM is fun. (3) part of the problem solution and summary
- After setting up the database and website When you open the app for testing, it shows that the server is being maintained
- Haut OJ 1401: praise energy
- 剑指 Offer 58 - II. 左旋转字符串
- Programmers' experience of delivering takeout
- Control Unit 控制部件
- Web APIs DOM node
- 动漫评分数据分析与可视化 与 IT行业招聘数据分析与可视化
- Drawing dynamic 3D circle with pure C language
猜你喜欢
随机推荐
对象的序列化
Solon 框架如何方便获取每个请求的响应时间?
Yolov5 ajouter un mécanisme d'attention
质量体系建设之路的分分合合
Hang wait lock vs spin lock (where both are used)
Developing desktop applications with electron
[merge array] 88 merge two ordered arrays
使用Room数据库报警告: Schema export directory is not provided to the annotation processor so we cannot expor
Download xftp7 and xshell7 (official website)
[to be continued] [UE4 notes] L2 interface introduction
Merge sort
Shell Sort
26、 File system API (device sharing between applications; directory and file API)
剑指 Offer 35.复杂链表的复制
使用Electron开发桌面应用
Introduction to tools in TF-A
Support multi-mode polymorphic gbase 8C database continuous innovation and heavy upgrade
剑指 Offer 58 - II. 左旋转字符串
Reflection summary of Haut OJ freshmen on Wednesday
kubeadm系列-00-overview








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