数据结构之队列结构以及优先级队列
创建一个队列结构
function Queue() {
this.container = [];
}
Queue.prototype = {
constructor: Queue,
// 进入队列 element进入队列的元素
enter: function (element) {
this.container.push(element)
},
// 移除队列
leave: function () {
if (this.container.length === 0) return
return this.container.shift();
},
// 查看队列长度
size: function () {
return this.container.length
},
// 查看队列内容
value: function () {
// 深拷贝是为了保证后期外面接收到的结果无论怎么操作都不会影响容器内的数据
return JSON.parse(JSON.stringify(this.container))
}
}
练习
n个人在一起玩游戏,从1开始数,数到m的人自动淘汰,最后剩下的人会取得胜利,问最后胜利的会是哪一位。
function game(n, m) {
let qe = new Queue();
// 先把人一次进入到队列中
for (let i = 1; i <= n; i++) {
qe.enter(i)
}
// 开始处理
while (qe.size() > 1) {
for (let i = 0; i < m - 1; i++) {
// 喊到关键数之前的先移除掉 在进到队列中
qe.enter(qe.leave())
}
qe.leave();
}
return qe.value()[0];
}
let res = game(6,4)
console.log(res,'res')
优先级队列
function Queue() {
this.container = [];
}
Queue.prototype = {
constructor: Queue,
// 进入队列 priority优先级 默认值为0,数值越大,优先级越高
enter: function enter(element, priority=0) {
let obj = {
value: element,
priority: priority
}
if (priority == 0) {
// 不指定优先级 (最小优先级):存储到末尾即可
this.container.push(obj)
return
}
// 指定优先级,我们需要从最后一项依次来比较
let flag = false;
for (let i = this.container.length - 1; i >= 0; i--) {
let item = this.container[i];
// console.log(item,'item')
if (item.priority >= priority){
// 插入到比较项的后面
this.container.splice(i+1,0,obj);
flag = true;
break;
}
};
// 没有比我优先级高的,我就是最高的优先级,插入到容器最开始的位置即可
!flag ? this.container.unshift(obj):null;
},
// 移除队列
leave: function () {
if (this.container.length === 0) return
return this.container.shift();
},
// 查看队列长度
size: function () {
return this.container.length
},
// 查看队列内容
value: function () {
// 深拷贝是为了保证后期外面接收到的结果无论怎么操作都不会影响容器内的数据
return JSON.parse(JSON.stringify(this.container))
}
}
let qe = new Queue();
qe.enter(1,2);
qe.enter(2);
qe.enter(3,1);
qe.enter(4,4);
qe.enter(5,1);
console.log(qe.container)