在JavaScript中实现队列
Liuyi 2021-07-06 队列
# 队列数据结构
队列是一种遵循先入先出(FIFO)规则的数据结构。第一个队列中的项目(输入)是第一个出队(输出)的。
队列有两个指针: 队首跟队尾。最先进入队列进行排队的项目位于队首,而最后进入队列的项目位于队尾。
# 队列的时间复杂度
惯有队列的所有操作的重点: enqueue, dequeue, peek 和length必须以常数时间复杂度o(1)执行。
class Queue {
constructor() {
this.items = {};
this.headIndex = 0;
this.tailIndex = 0;
}
enqueue(item) {
this.items[this.tailIndex] = item;
this.tailIndex++
}
dequeue() {
const item = this.items[this.headIndex];
delete this.items[this.headIndex];
this.headIndex++;
return item;
}
peek() {
return this.items[this.headIndex];
}
get length() {
return this.tailIndex - this.headIndex;
}
}
const queue = new Queue();
queue.enqueue(4);
queue.enqueue(7);
queue.enqueue(2);
queue.enqueue(6);
console.log(queue.dequeue(),queue.peek(), queue.length)
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
39
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
39