# 队列
FIFO: First In First Out(先进先出)
wikipedia: https://zh.wikipedia.org/wiki/%E9%98%9F%E5%88%97 (opens new window)
# 数组实现
const queue = []
// 入队
queue.push(0)
queue.push(1)
queue.push(2)
// 出队
const shiftVal = queue.shift() // 0
console.log(queue) // [1, 2]
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 双栈实现队列
点击查看代码
/**
* 队列
*/
class CQueue {
constructor() {
this.inStack = []
this.outStack = []
}
// 入队
appendTail(value) {
this.inStack.push(value)
}
// 出队
deleteHead() {
const { inStack, outStack } = this
if (outStack.length > 0) return outStack.pop()
while(inStack.length) {
outStack.push(inStack.pop())
}
return outStack.pop() || -1
}
}
// ---------- Test ---------
let cqueue = new CQueue()
cqueue.appendTail(0)
cqueue.appendTail(1)
cqueue.appendTail(2)
cqueue.deleteHead()
cqueue.deleteHead()
console.log(cqueue)
// CQueue { inStack: [], outStack: [2] }
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
34
35
36
37
38
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
34
35
36
37
38