Javascript中的队列

时间:2024-01-08 22:19:56

队列遵循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.size=function () {
return items.length;
}
// 打印
this.print=function(){
console.log(items.toString());
}
}

  优先级队列

function PriorityQueue() {
var items=[];
function QueueElement(element,priority) {
this.element=element;
this.priority=priority;
}
// priority 数值越大,优先级越低
this.enqueue=function (element,priority) {
var queueElement=new QueueElement(element,priority);
if(this.isEmpty()){
items.push(queueElement);
}else{
var added=false;
for (var 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.print=function(){
console.log(JSON.stringify(items));
}
}

通过击鼓传花演示循环队列

function hotPotato(nameList,num){
var queue=new Queue(),eliminated="";
for (var i = 0; i < nameList.length; i++) {
queue.enqueue(nameList[i]);
}
while (queue.size()>1) {
for (var i = 0; i < num; i++) {
queue.enqueue(queue.dequeue());
}
eliminated=queue.dequeue();
console.log(eliminated+"被淘汰");
}
return queue.dequeue();
}