用栈模拟队列

又是一道被面试题,虽然据说是基础题,但是方法还是很巧妙,值得马克。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Stack {
constructor() {
this.stack = [];
}
pop () {
return this.stack.pop();
}
push (...args) {
this.stack.push(...args);
}
}

class Queue {
constructor() {
this.inStack = new Stack;
this.outStack = new Stack;
}
enqueue(...args) {
this.inStack.push(...args);
}
dequeue() {
let res = this.outStack.pop();
if (typeof res === 'undefined') {
let temp = this.inStack.pop();
while (typeof temp !== 'undefined') {
this.outStack.push(temp);
temp = this.inStack.pop();
}
res = this.outStack.pop();
}
return res;
}
}