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

114 lines
3.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [ Offer 09. ](https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/)
easy
![](https://img-blog.csdnimg.cn/20210320141325908.gif)
```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]
```
Cqueue()appendTailstackAdeleteHeadstackB
appendTail
[ Offer 09. ](https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/)去实现一下,下面我们看代码。
Java Code:
```java
class CQueue {
//初始化两个栈
Stack<Integer> stack1,stack2;
public CQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
//入队,我们往第一个栈压入值
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();
}
}
```
JS Code:
```javascript
var CQueue = function() {
this.stack1 = [];
this.stack2 = [];
};
CQueue.prototype.appendTail = function(value) {
this.stack1.push(value);
};
CQueue.prototype.deleteHead = function() {
if (!this.stack2.length) {
while(this.stack1.length) {
this.stack2.push(this.stack1.pop());
}
}
return this.stack2.pop() || -1;
};
```