forked from ohxxx/algorithm-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.js
More file actions
78 lines (63 loc) · 1.67 KB
/
Copy pathqueue.js
File metadata and controls
78 lines (63 loc) · 1.67 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class Queue {
constructor() {
this.count = 0 // 控制队列大小
this.lowestCount = 0 // 追踪第一个元素
this.items = {} // 队列
}
/** 向队列添加元素 */
enqueue(element) {
this.items[this.count] = element;
this.count++
}
/** 从队列中移除元素 */
dequeue() {
if (this.isEmpty()) return null;
const temp = this.items[this.lowestCount] // 暂存队首数据,用来返回数据
delete this.items[this.lowestCount] // 出队,即删除队列中第一个元素
this.lowestCount++; // 出队后将队首的标记移到第二位
return temp
}
/** 查看队列头元素 */
peek() {
if (this.isEmpty()) return null;
return this.items[this.lowestCount]
}
/** 检查队列是否为空,并获取它的长度 */
isEmpty() {
return this.size() === 0;
}
/** 查看队队列个数 */
size() {
return this.count - this.lowestCount
}
/** 清空队列 */
clear() {
this.count = 0
this.lowestCount = 0
this.items = {}
}
/** 拓展-输出当前队列 */
toString() {
if (this.isEmpty()) return '';
let objString = `${this.items[this.lowestCount]}`
for (let i = this.lowestCount + 1; i < this.count; i++) {
objString = `${objString},${this.items[i]}`
}
return objString
}
}
module.exports = Queue
// test
// const xxx = new Queue()
// xxx.enqueue('111')
// xxx.enqueue('222')
// xxx.enqueue('333')
// console.log('dequeue', xxx.dequeue());
// console.log('peek', xxx.peek());
// console.log('size', xxx.size());
// console.log('toString', xxx.toString());
// setTimeout(() => {
// xxx.clear()
// console.log(xxx);
// }, 1000)
// console.log(xxx);