当前位置:网站首页>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(); */
}
}
边栏推荐
- Introduction to tools in TF-A
- Haut OJ 1245: large factorial of CDs --- high precision factorial
- Improvement of pointnet++
- 使用Room数据库报警告: Schema export directory is not provided to the annotation processor so we cannot expor
- Maximum number of "balloons"
- Remote upgrade afraid of cutting beard? Explain FOTA safety upgrade in detail
- Solution to the palindrome string (Luogu p5041 haoi2009)
- TF-A中的工具介绍
- 动漫评分数据分析与可视化 与 IT行业招聘数据分析与可视化
- 一个新的微型ORM开源框架
猜你喜欢
随机推荐
[转]MySQL操作实战(一):关键字 & 函数
剑指 Offer 35.复杂链表的复制
Bubble sort summary
Corridor and bridge distribution (csp-s-2021-t1) popular problem solution
Download xftp7 and xshell7 (official website)
[转]:Apache Felix Framework配置属性
利用HashMap实现简单缓存
二十六、文件系统API(设备在应用间的共享;目录和文件API)
[to be continued] I believe that everyone has the right to choose their own way of life - written in front of the art column
远程升级怕截胡?详解FOTA安全升级
Software test -- 0 sequence
Double pointer Foundation
Detailed explanation of expression (csp-j 2021 expr) topic
Merge sort
剑指 Offer 06.从头到尾打印链表
浅谈JVM(面试常考)
kubeadm系列-02-kubelet的配置和启动
剑指 Offer 58 - II. 左旋转字符串
[to be continued] [depth first search] 547 Number of provinces
Time complexity and space complexity