方法
- 入队
- 出队
- 查看队首
- 查看长度
实现
function Queue() {
this.list = [];
// 进队
Queue.prototype.enqueue = function (item) {
this.list.push(item);
};
// 出队
Queue.prototype.dequeue = function () {
return this.list.shift();
};
// 查看下一个该出队的
Queue.prototype.front = function () {
return this.list[0] || null;
};
// 长度 size
Queue.prototype.size = function () {
return this.list.length;
};
}
功能测试
const myQ = new Queue();
console.log(myQ.size()); // 0
myQ.enqueue("阿西");
myQ.enqueue("阿拉");
myQ.enqueue("阿吧");
console.log(myQ.size()); // 3
console.log(myQ.front()); // 阿西
myQ.dequeue();
console.log(myQ.size()); // 2
console.log(myQ.front()); // 阿拉
myQ.dequeue();
myQ.dequeue();
console.log(myQ.size()); // 0
console.log(myQ.front()); // null
优先级队列(越大优先级越高)
方法
- 入队
- 出队
- 查看队首
- 查看长度
实现
function PriorityQueue() {
this.list = [];
function createNode(item, priority) {
return {
value: item,
priority,
};
}
// 长度
PriorityQueue.prototype.size = function () {
return this.list.length;
};
// 入队
PriorityQueue.prototype.enqueue = function (item, priority) {
if (this.size() < 1) {
this.list.push(createNode(item, priority));
} else {
// 数字越大优先级越高 可使用二分法判断插入位置进行优化
let add = false;
for (let i = 0; i < this.list.length; i++) {
const element = this.list[i];
if (element.priority <= priority) {
this.list.splice(i, 0, createNode(item, priority));
add = true;
break;
}
}
!add && this.list.push(createNode(item, priority));
}
};
// 出队
PriorityQueue.prototype.dequeue = function () {
return this.list.shift();
};
// 下一个
PriorityQueue.prototype.front = function () {
return this.list[0].value || null;
};
}
功能测试
const myPQ = new PriorityQueue();
console.log(myPQ.size()); // 0
myPQ.enqueue(3, 3);
myPQ.enqueue(1, 1);
console.log(myPQ.size()); // 2
console.log(myPQ.front()); // 3
myPQ.dequeue();
myPQ.enqueue(33, 33);
myPQ.enqueue(2, 2);
myPQ.enqueue(9, 9);
console.log(myPQ.size()); // 4
console.log(myPQ.front()); // 33
myPQ.dequeue();
myPQ.dequeue();
myPQ.dequeue();
myPQ.dequeue();
console.log(myPQ.size()); // 0
console.log(myPQ.front()); // null
实现击鼓传花游戏
简介
参加活动的若干人,指定一个数字,淘汰掉第n个人,重新数再淘汰掉第n个人,一直到最后一个
实现
// 基于队列
function passGame(peoples, num) {
const arr = new Queue();
peoples.forEach((item) => {
arr.enqueue(item);
});
// 长度为1个时 停止循环
while (arr.size() > 1) {
let i = 1;
// 一直出队并入队 第n个只出队
while (i < num) {
arr.enqueue(arr.dequeue());
i++;
}
arr.dequeue();
}
return arr.front();
}
测试
passGame(['job', 'air', 'lily', 'aci', 'no', 'bar'], 9); // 'no'
passGame(['job', 'air', 'lily', 'aci', 'no', 'bar'], 3); // 'job'
passGame(['job', 'air', 'lily', 'aci', 'no'], 4); // 'job'
passGame(['job', 'air', 'lily', 'aci'], 5); // 'air'
passGame(['air', 'aci', 'bar'], 2); // 'bar'
passGame(['air', 'aci', 'bar'], 6); // 'air'
passGame(['air', 'aci', 'bar'], 1); // 'bar'
参考
- 小马哥 – JS数据结构与算法