-
Notifications
You must be signed in to change notification settings - Fork 0
/
queueDemo.js
86 lines (81 loc) · 2.1 KB
/
queueDemo.js
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
79
80
81
82
83
84
85
86
function Queue() {
let items = [];
this.enqueue = function (element) {
items.push(element);
};
this.dequeue = function () {
return items.shift();
};
this.front = function () {
return items[0] ? items[0] : "数组为空";
};
this.isEmpty = function () {
return items.length === 0;
};
this.size = function () {
return items.length;
};
this.print = function () {
console.log(items.toString());
};
}
// 循环队列,模拟击鼓传花
function hotPotato(nameList, num) {
let queue = new Queue();
for (let i = 0; i < nameList.length; i++) {
queue.enqueue(nameList[i]);
}
let result = "";
while (queue.size() > 1) {
for (let i = 0; i < num; i++) {
queue.enqueue(queue.dequeue());
}
result = queue.dequeue();
console.log(`${result} 被淘汰了`);
}
console.log(queue.dequeue() + "是最后的胜利者");
}
let names = ["feng", "gping", "ling", "qing", "zeng"];
hotPotato(names, 4);
// 最小优先队列的实现
function PriorityQueue() {
let items = [];
function QueueElement(element, priority) {
this.element = element;
this.priority = priority;
}
this.enqueue = function (element, priority) {
let queueElement = new QueueElement(element, priority);
let add = false;
// items.forEach((item, index) => {
// if (queueElement.priority < item.priority) {
// items.splice(index, 0, queueElement);
// add = true;
// break; // forEach 中不能使用break
// }
// })
for (let index = 0; index < items.length; index++) {
if (queueElement.priority < items[index].priority) {
items.splice(index, 0, queueElement);
add = true;
break;
}
}
if (!add) {
items.push(queueElement);
}
};
this.print = function () {
items.forEach((item, index) => {
console.dir(item); // 使用 dir 可以输出对象
// console.dir(`item: ${item},index: ${index}`);
});
};
}
let queue = new PriorityQueue();
queue.enqueue(1, 2);
queue.print();
queue.enqueue(2, 1);
queue.print();
queue.enqueue(3, 4);
queue.print();