<script>
//创建一个队列
function Queue(){
let items = [];
//向队尾添加一个新的项
this.enqueue = function(element){
items.push(element)
} //移除队列第一个项,并返回被移除的元素 dequeue
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;
}
} //使用
// var queue = new Queue(); //循环队列
//游戏击鼓传花
function flowersGama(nameList,number){
var queue = new Queue();
for(let i=0;i<nameList.length;i++){
queue.enqueue(nameList[i]);
}
var failers = '';
while(queue.size()>1){
for(let i=0;i<number;i++){
queue.enqueue(queue.dequeue());
}
failers = queue.dequeue();
console.log(failers + '被淘汰了');
}
return queue.dequeue();
}
var names = ['John','Jack','Camila','Ingrid','Carl'];
var winner = flowersGama(names, 7);
console.log('胜利者:' + winner); //优先队列 function PriorityQueue(){
let items = []; function QueueElement(element,priority){
this.element = element;
this.priority = priority;
}
//优先队列插入
this.enqueue = function(element,priority){
var queueElement = new QueueElement(element,priority);
if(this.isEmpty()){
items.push(queueElement);
}else{
var 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.isEmpty = function(){
return items.length === 0;
} this.print = function(){
console.log(items)
}
}
var priorityQueue = new PriorityQueue();
priorityQueue.enqueue("John", 2);
priorityQueue.enqueue("Jack", 1);
priorityQueue.enqueue("Camila", 1);
priorityQueue.print();
</script>