队列
队列是一种受限的线性表,先进先出(FIFO)
- 只允许在表的前端进行删除操作
- 在表的后端进行插入操作
队列的实现
数组实现
function Queue() {
this.items = [];
// 加入队列
Queue.prototype.enqueue = function (element) {
this.items.push(element)
}
// 出队列
Queue.prototype.dequeue = function (element) {
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 = ''
this.items.forEach(element => {
str += element + " ";
});
return str;
}
}
击鼓传花问题
function game(list, num) {
const queue = new Queue()
// 数组元素加入队列
for (let index = 0; index < list.length; index++) {
queue.enqueue(list[index]);
}
// 队列剩余不是一个就继续循环
while (queue.size() > 1) {
// num数字前的元素取出,放入队列末尾
for (let index = 0; index < num - 1; index++) {
queue.enqueue(queue.dequeue());
}
// 删除num对应的元素
queue.dequeue()
}
// 取出最后一个元素
const end = queue.front()
alert(end)
// 返回最后元素的下标
return list.indexOf(end)
}
const names= ['张三','李四','王五','赵六','荣七']
alert(game(names,3))