Skip to content

docs: add a description of the solution #643

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 31 additions & 30 deletions lcof/面试题09. 用两个栈实现队列/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@

## 解法

- 两个栈,一个负责输入,一个负责输出
- 入队的元素放入输入栈当中
- 当出队时,将输入栈当中的所有元素出栈,放入输出栈当中,让栈底的元素跑到最上面来
- 只有输出栈中没有元素时才进行倒放,不必每一次出队前都进行进行倒放

<!-- tabs:start -->

### **Python3**
Expand Down Expand Up @@ -65,33 +70,29 @@ class CQueue:
### **Java**

```java
import java.util.Stack;

class CQueue {
private Stack<Integer> stack_1;
private Stack<Integer> stack_2;
Comment on lines +76 to +77
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Java 栈不推荐使用 Stack,而应该使用 ArrayDeque。另外,Java 不使用下划线命名变量,可以改为 stk1, stk2


private Deque<Integer> s1;
private Deque<Integer> s2;
public CQueue() {
s1 = new ArrayDeque<>();
s2 = new ArrayDeque<>();
stack_1 = new Stack<>();
stack_2 = new Stack<>();
}

public void appendTail(int value) {
s1.push(value);
if (s2.isEmpty()) {
move();
}
stack_1.push(value);
}

public int deleteHead() {
if (s2.isEmpty()) {
move();
if (stack_2.empty()) {
while (!stack_1.empty()) {
stack_2.push(stack_1.pop());
}
}
return s2.isEmpty() ? -1 : s2.pop();
}

private void move() {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
return stack_2.empty() ? -1 : stack_2.pop();
}
}

Expand All @@ -107,32 +108,32 @@ class CQueue {

```js
var CQueue = function () {
this.data = [];
this.helper = [];
this.data = [];
this.helper = [];
};
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function (value) {
this.data.push(value);
this.data.push(value);
};
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function () {
if (this.data.length) {
while (this.data.length > 1) {
this.helper.push(this.data.pop());
}
let res = this.data.pop();
while (this.helper.length) {
this.data.push(this.helper.pop());
if (this.data.length) {
while (this.data.length > 1) {
this.helper.push(this.data.pop());
}
let res = this.data.pop();
while (this.helper.length) {
this.data.push(this.helper.pop());
}
return res;
} else {
return -1;
}
return res;
} else {
return -1;
}
};
```

Expand Down