JavaScript队列结构——击鼓传花游戏
function Queue(){
this.items = []
Queue.prototype.enqueue = function(item){
this.items.push(item)
}
Queue.prototype.dequeue = 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
}
Queue.prototype.toString = function(){
return this.items.join(' ')
}
}
function passGame(players , num){
const queue = new Queue()
players.forEach(item => {
queue.enqueue(item)
})
while(queue.items.length > 1){
for (let i = 0; i < num - 1; i++){
queue.enqueue(queue.dequeue())
}
queue.dequeue()
}
const winner = queue.front()
console.log('获胜者为:' + winner)
return winner
}