algorithm-base/animation-simulation/栈和队列/剑指Offer09用两个栈实现队列.md

112 lines
3.7 KiB
Java
Raw Normal View History

2021-07-23 15:44:19 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
2021-03-20 08:57:12 +00:00
>
>
>
2021-07-23 15:44:19 +00:00
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-20 08:57:12 +00:00
2021-03-20 06:12:22 +00:00
#### [ Offer 09. ](https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/)
2021-07-23 15:44:19 +00:00
easy
2021-03-19 10:50:39 +00:00
2021-03-20 06:19:50 +00:00
![](https://img-blog.csdnimg.cn/20210320141325908.gif)
2021-03-19 10:50:39 +00:00
```java
class CQueue {
//创建队列
public CQueue() {
}
//入队
public void appendTail(int value) {
}
//出队
public int deleteHead() {
}
}
```
1
```java
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
[null,null,3,-1]
```
2
```java
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
[null,-1,null,null,5,2]
```
2021-07-23 15:44:19 +00:00
Cqueue ()appendTail stackA deleteHead stackB
2021-03-19 10:50:39 +00:00
2021-07-23 15:44:19 +00:00
appendTail
2021-03-19 10:50:39 +00:00
[ Offer 09. ](https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/)去实现一下,下面我们看代码。
2021-04-27 10:13:37 +00:00
Java Code:
2021-07-23 15:44:19 +00:00
2021-03-19 10:50:39 +00:00
```java
class CQueue {
//初始化两个栈
Stack<Integer> stack1,stack2;
public CQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
2021-07-23 15:44:19 +00:00
2021-03-19 10:50:39 +00:00
}
//入队,我们往第一个栈压入值
public void appendTail (int value) {
stack1.push(value);
}
//出队
public int deleteHead() {
//大家可以自己思考一下为什么if条件为stack2.isEmpty(),细节所在
if (stack2.isEmpty()) {
//如果此时A栈没有值则直接-1我们可以看示例
if (stack1.isEmpty()) {
return -1;
}
//将A栈的值压入B栈中
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
```
2021-04-27 10:13:37 +00:00
JS Code:
2021-07-23 15:44:19 +00:00
2021-04-27 10:13:37 +00:00
```javascript
2021-07-23 15:44:19 +00:00
var CQueue = function () {
this.stack1 = [];
this.stack2 = [];
2021-04-27 10:13:37 +00:00
};
2021-07-23 15:44:19 +00:00
CQueue.prototype.appendTail = function (value) {
this.stack1.push(value);
2021-04-27 10:13:37 +00:00
};
2021-07-23 15:44:19 +00:00
CQueue.prototype.deleteHead = function () {
if (!this.stack2.length) {
while (this.stack1.length) {
this.stack2.push(this.stack1.pop());
2021-04-27 10:13:37 +00:00
}
2021-07-23 15:44:19 +00:00
}
return this.stack2.pop() || -1;
2021-04-27 10:13:37 +00:00
};
```