队列是遵循FIFO(先进先出)原则。
循环队列是修改版的队列实现。
击鼓传花游戏的代码如下:
function Queue() {//队列类
var items = [];
this.enqueue = function (element) {
items.push(element);
}
this.dequeue = function () {
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());
}
}
function hotPotato(nameList, num) {//nameList为姓名数组,num为一个数字用来迭代队列
var queue = new Queue();
for (var i = 0; i < nameList.length; i++) {
queue.enqueue(nameList[i]);//数组入队
}
var eliminated = '';
while (queue.size() > 1) {
for (var i = 0; i < num; i++) {
queue.enqueue(queue.dequeue());//数组出队然后入队
}
eliminated = queue.dequeue();
console.log(eliminated + '在击鼓传花游戏中被淘汰。');
}
return queue.dequeue();
}
var names=['John','Jack','Camila','Ingrid','Carl'];
var winner=hotPotato(names,7);
console.log('胜利者是:'+winner);