完整的模拟队列的实现:
function Queue() {
let items = [];
this.enqueue = function (element) {
items.push(element);
};
this.dequeue = function () {
return items.shift();
};
this.front = function () {
return items[0];
};
this.isEmpty = function () {
return items.length === 0;
};
this.clear = function () {
items = [];
};
this.size = function () {
return items.length;
};
this.print = function () {
console.log(items.toString());
};
}
优先队列:元素的添加和移除是基于优先级的,比较常见的用法就是登机顺序啦,头等舱和商务仓的登机顺序要比经济舱的前,还有医院的急诊挂号呀,女士优先的权限呀等都是优先队列的应用。
如果队列为空,则直接添加进队列,这时因为它是第一个队列元素,优先级肯定是第一的,没有元素跟它比;其后的元素添加进队列要比较它们的优先级,优先级 priority 值小的就靠前(最小优先级队列,1级的优先级是最靠前的,优先级小的元素会被放置在队列的前面);也可以按照最大优先级队列(类似于会员等级高的优先级靠前);
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);
if(this.isEmpty()){
items.push(queueElement);
}else{
let added = false;
for(let i = 0; i<items.length; i++){
if(queueElement.priority < items[i].priority){
items.splice(i,0,queueElement);
added = true;
break;
}
}
if(!added){
items.push(queueElement);
}
}
};
this.dequeue = function () {
return items.shift();
};
this.front = function () {
return items[0];
};
this.isEmpty = function () {
return items.length === 0;
};
this.size = function () {
return items.length;
};
this.clear = function () {
items = [];
};
this.print = function () {
for(let i = 0; i<items.length; i++){
console.log(items[i].element + "-" + items[i].priority);
}
};
}
let priorityQueue = new PriorityQueue();
priorityQueue.enqueue("John", 2);
priorityQueue.enqueue("Jack",1);
priorityQueue.enqueue("Tom",1);
priorityQueue.print(); //Jack-1 Tom-1 John-2
console.log(priorityQueue.size()); // 3
循环队列:
function hotPotato(nameList, num) {
let queue = new Queue();
for(let i = 0; i<nameList.length; i++){
queue.enqueue(nameList[i]);
}
let elimated = '';
while(queue.size() > 1){
for(let i = 0; i<num; i++){
queue.enqueue(queue.dequeue());
}
elimated = queue.dequeue();
console.log(elimated + '在击鼓传花游戏中被淘汰');
}
return queue.dequeue();
}
let names = ["John", "Pony", "Tom", "Amy", "Sam"];
let winner = hotPotato(names, 2);
console.log('生者: ' + winner);
/*Tom在击鼓传花游戏中被淘汰
*John在击鼓传花游戏中被淘汰
*Sam在击鼓传花游戏中被淘汰
* Pony在击鼓传花游戏中被淘汰
* 生者: Amy
* */
模拟一个顺序传物,物件在谁手上就被淘汰的游戏。用到循环队列。按照名字数组的顺序传递,每次传递都会有人拿到那个物件,也就是说每次传递都会有人被淘汰,给定一个数字num ,迭代队列,从队列开头移除一项,再将其添加到队尾,一旦达到传递的次数,那个人就会被淘汰,就从队列中被移除(queue.dequeue()方法);最后剩下一个人的时候,就是胜利者。