Queue 类 定义
队列是遵循FIFO(First In First Out,先进先出,也称为先来先服务)原则的一组有序的项。
队列在尾部添加新元素,并从顶部移除元素。最新添加的元素必须排在队列的末尾
function Queue() {
var 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());
};
}
// 后面的 通过 var newQueue = new Queue( ) 来进行使用
优先队列
元素的添加和移除是基于优先级的。一个现实的例子就是机
场登机的顺序。头等舱和商务舱乘客的优先级要高于经济舱乘客。
实现一个优先队列,有两种选项:设置优先级,然后在正确的位置添加元素;或者用入列操
作添加元素,然后按照优先级移除它们。
function PriorityQueue() {
var items = [];
function QueueElement (element, priority){ // {1}
this.element = element;
this.priority = priority;
}
this.enqueue = function(element, priority){
var queueElement = new QueueElement(element, priority);
if (this.isEmpty()){
items.push(queueElement); // {2}
} else {
var added = false;
for (var i=0; i < items.length; i++){
if (queueElement.priority < items[i].priority){
items.splice(i,0,queueElement); //{3}
added=true;
break; // {4}
}
}
if (!added){ //{5}
items.push(queueElement);
}
}
};
//其他方法和默认的Queue实现相同
}
循环队列——击鼓传花(Hot Potato)
function hotPotato (nameList, num){
var queue = new Queue(); // {1}
for (var i=0; i < nameList.length; i++){
queue.enqueue(nameList[i]); // {2}
}
var eliminated='' ;
while (queue.size()> 1){
for (var i=0; i < num; i++){
queue.enqueue(queue.dequeue()); // {3}
}
eliminated=queue.dequeue();// {4}
console.log(eliminated + '在击鼓传花游戏中被淘汰。 ' );
}
return queue.dequeue();// {5}
}
var names=['John','Jack','Camila','Ingrid','Carl'];
var winner=hotPotato(names, 7);
console.log('胜利者: ' + winner);
实现一个模拟的击鼓传花游戏,要用到这一章开头实现的Queue类(行{1})。我们会得到一
份名单,把里面的名字全都加入队列(行{2})。给定一个数字,然后迭代队列。从队列开头移
除一项,再将其添加到队列末尾(行{3}),模拟击鼓传花(如果你把花传给了旁边的人,你被
淘汰的威胁立刻就解除了)。一旦传递次数达到给定的数字,拿着花的那个人就被淘汰了(从队
列中移除——行{4})。最后只剩下一个人的时候,这个人就是胜者(行{5})。