js实现队列

一、队列

队列是线性结构,遵循先进先出,在队尾添加新元素,并从顶部移除元素
现实生活中最常见的就是排队,先来先服务

二、js实现队列

使用对象模拟队列,主要实现以下五个方法:
enqueue: 元素进入队列
dequeue: 元素出队列
peek: 获取队头元素
isEmpty: 判断队列是否为空
size: 获取队列元素个数

function Queue() {
  this.count = 0;
  this.lowestCount = 0;
  this.items = {};
}

Queue.prototype.enqueue = function (element) {
  this.items[this.count] = element;
  this.count++;
};

Queue.prototype.dequeue = function () {
  if (this.isEmpty()) {
    return undefined;
  }
  const result = this.items[this.lowestCount];
  delete this.items[this.lowestCount];
  this.lowestCount++;
  return result;
};

Queue.prototype.peek = function () {
  if (this.isEmpty()) {
    return undefined;
  }
  return this.items[this.lowestCount];
};

Queue.prototype.isEmpty = function () {
  return this.size() === 0;
};

Queue.prototype.size = function () {
  return this.count - this.lowestCount;
};

三、队列应用-击鼓传花游戏

游戏规则是,输入一个队列和一个传递次数,从第一个位置开始计数,数到传递次数就淘汰这个元素,然后重新计数,依次淘汰,直到只剩下一个元素就是胜利者,输出这个元素。实现思路:用队列模拟,不断将队尾元素加入队头,循环到传递次数,淘汰队头,然后重新循环,知道队列中只有一个元素,输出这个元素,下面就是击鼓传花游戏的实现:需要用到上文封装好的队列

let { Queue } = require("./队列");

function hotPotato(elementList, num) {
  let queue = new Queue();
  elementList.forEach((element) => {
    queue.enqueue(element);
  });
  while (queue.size() > 1) {
    for (let i = 0; i < num; i++) {
      queue.enqueue(queue.dequeue());
    }
    queue.dequeue();
  }
  return queue.dequeue();
}

let name = [1, 2, 3, 4, 5];
console.log(hotPotato(name, 7));
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值