// 基于数组封装一个队列
function Queue() {
this.items = [];
// 将数据存入队列中
Queue.prototype.entryQueue = function (ele) {
return this.items.push(ele)
}
// 数据出队列
Queue.prototype.outQueue = function () {
return this.items.shift()
}
// 查看队列的第一个数据信息
Queue.prototype.front = function () {
return this.items[0]
}
// 判断队列是否为空
Queue.prototype.isEmpty = function () {
return this.items.length == 0
}
// 队列的长度
Queue.prototype.size = function () {
return this.items.length
}
// toString
Queue.prototype.toString = function () {
let str = '';
for (let i = 0; i < this.items.length; i++) {
str += this.items[i] + ' '
}
return str
}
}
let q = new Queue();
q.entryQueue(11);
q.entryQueue(22);
q.entryQueue(33);
q.entryQueue(44);
// 击鼓传花
function passName(nameList, num) {
let q = new Queue();
// 将数据依次放入队列中
for (let i = 0; i < nameList.length; i++) {
q.entryQueue(nameList[i])
}
// 游戏开始,当只剩一人时,游戏结束
while (q.size() > 1) {
// 将没被淘汰的依次进行出列,入列
for (let j = 0; j < num - 1; j++) {
q.entryQueue(q.outQueue())
}
// 淘汰的出列
q.outQueue()
}
let name = q.front();
return '游戏胜利的是' + name + ',他所在的位置是' + nameList.indexOf(name)
}
let nameList = ['lisi', 'zhaoGao', 'feifei', 'tom', 'jay', 'maria'];
console.log(passName(nameList, 5)); // 游戏胜利的是lisi,他所在的位置是0