当前位置:网站首页>剑指 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(); */
}
}
边栏推荐
- [allocation problem] 135 Distribute candy
- Warning using room database: schema export directory is not provided to the annotation processor so we cannot export
- kubeadm系列-02-kubelet的配置和启动
- [turn to] MySQL operation practice (III): table connection
- Optimization scheme of win10 virtual machine cluster
- [es practice] use the native realm security mode on es
- Developing desktop applications with electron
- Chapter 6 data flow modeling - after class exercises
- Add level control and logger level control of Solon logging plug-in
- 2022上半年全国教师资格证下
猜你喜欢
![[轉]: OSGI規範 深入淺出](/img/54/d73a8d3e375dfe430c2eca39617b9c.png)
[轉]: OSGI規範 深入淺出

Grail layout and double wing layout

Learning notes of "hands on learning in depth"

Talking about JVM (frequent interview)

Research on the value of background repeat of background tiling
![[depth first search] 695 Maximum area of the island](/img/08/cfff4aec667216e4f146205a12c13f.jpg)
[depth first search] 695 Maximum area of the island

SAP method of modifying system table data
![[trans]: spécification osgi](/img/54/d73a8d3e375dfe430c2eca39617b9c.png)
[trans]: spécification osgi

lxml.etree.XMLSyntaxError: Opening and ending tag mismatch: meta line 6 and head, line 8, column 8

On-off and on-off of quality system construction
随机推荐
Count sort
Haut OJ 1316: sister choice buys candy III
Development error notes
Haut OJ 1321: mode problem of choice sister
Es module and commonjs learning notes -- ESM and CJS used in nodejs
[depth first search] 695 Maximum area of the island
Learning notes of "hands on learning in depth"
MySQL数据库(一)
Quick sort summary
sync. Interpretation of mutex source code
[allocation problem] 135 Distribute candy
一个新的微型ORM开源框架
Haut OJ 1401: praise energy
Service fusing hystrix
JVM call not used once in ten years
object serialization
Find a good teaching video for Solon framework test (Solon, lightweight application development framework)
记录QT内存泄漏的一种问题和解决方案
YOLOv5添加注意力機制
[sum of two numbers] 169 sum of two numbers II - enter an ordered array