当前位置:网站首页>剑指 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(); */
}
}
边栏推荐
- [es practice] use the native realm security mode on es
- 浅谈JVM(面试常考)
- C language Essay 1
- Haut OJ 1321: mode problem of choice sister
- Programmers' experience of delivering takeout
- object serialization
- 对象的序列化
- Demonstration of using Solon auth authentication framework (simpler authentication framework)
- [to be continued] I believe that everyone has the right to choose their own way of life - written in front of the art column
- 搭建完数据库和网站后.打开app测试时候显示服务器正在维护.
猜你喜欢

Pointnet++学习
![[to be continued] [depth first search] 547 Number of provinces](/img/c4/b4ee3d936776dafc15ac275d2059cd.jpg)
[to be continued] [depth first search] 547 Number of provinces

Embedded database development programming (V) -- DQL

挂起等待锁 vs 自旋锁(两者的使用场合)
![[paper notes] multi goal reinforcement learning: challenging robotics environments and request for research](/img/17/db8614b177f33ee4f67b7d65a8430f.png)
[paper notes] multi goal reinforcement learning: challenging robotics environments and request for research

Research on the value of background repeat of background tiling

读者写者模型

object serialization
![[轉]: OSGI規範 深入淺出](/img/54/d73a8d3e375dfe430c2eca39617b9c.png)
[轉]: OSGI規範 深入淺出

The present is a gift from heaven -- a film review of the journey of the soul
随机推荐
Es module and commonjs learning notes
Bucket sort
Research on the value of background repeat of background tiling
Haut OJ 1245: large factorial of CDs --- high precision factorial
JVM call not used once in ten years
Pointnet++的改进
The next key of win generates the timestamp file of the current day
[binary search] 69 Square root of X
利用HashMap实现简单缓存
小程序直播+电商,想做新零售电商就用它吧!
发现一个很好的 Solon 框架试手的教学视频(Solon,轻量级应用开发框架)
C语言杂谈1
Haut OJ 1357: lunch question (I) -- high precision multiplication
To be continued] [UE4 notes] L4 object editing
xftp7与xshell7下载(官网)
Romance of programmers on Valentine's Day
Haut OJ 1401: praise energy
支持多模多态 GBase 8c数据库持续创新重磅升级
TF-A中的工具介绍
YOLOv5添加注意力机制