返回

初探LeetCode 641:用JavaScript打造双向循环队列

前端

算法解析:双向循环队列的实现原理

双向循环队列是一种特殊的队列,它不仅支持先进先出(FIFO)的规则,还支持先进后出(LIFO)的规则,这使其更加灵活。同时,双向循环队列利用数组来存储数据,并使用两个索引(front和rear)来标记队首和队尾的位置。

代码实现:从零搭建双向循环队列

为了实现双向循环队列,我们首先需要创建一个容量为k的数组来存储数据,并定义两个变量:capacity表示队列的最大容量,front表示队首的索引。然后,我们可以编写以下代码:

class Deque {
  constructor(capacity) {
    this.capacity = capacity;
    this.front = 0;
    this.rear = capacity - 1;
    this.items = new Array(capacity);
  }

  // 入队(队尾)
  enqueueRear(item) {
    if (this.isFull()) {
      console.error("队列已满,无法入队");
      return;
    }
    this.items[this.rear] = item;
    this.rear = (this.rear + 1) % this.capacity; // 队尾索引循环
  }

  // 入队(队首)
  enqueueFront(item) {
    if (this.isFull()) {
      console.error("队列已满,无法入队");
      return;
    }
    this.front = (this.front - 1 + this.capacity) % this.capacity; // 队首索引循环
    this.items[this.front] = item;
  }

  // 出队(队首)
  dequeueFront() {
    if (this.isEmpty()) {
      console.error("队列已空,无法出队");
      return;
    }
    const item = this.items[this.front];
    this.front = (this.front + 1) % this.capacity;
    return item;
  }

  // 出队(队尾)
  dequeueRear() {
    if (this.isEmpty()) {
      console.error("队列已空,无法出队");
      return;
    }
    const item = this.items[this.rear];
    this.rear = (this.rear - 1 + this.capacity) % this.capacity;
    return item;
  }

  // 判断队列是否为空
  isEmpty() {
    return this.front === this.rear;
  }

  // 判断队列是否已满
  isFull() {
    return (this.rear + 1) % this.capacity === this.front;
  }

  // 获取队列长度
  size() {
    if (this.isEmpty()) {
      return 0;
    }
    if (this.rear > this.front) {
      return this.rear - this.front + 1;
    } else {
      return this.capacity - (this.front - this.rear - 1);
    }
  }
}

应用场景:双向循环队列在现实世界中的妙用

双向循环队列在现实世界中有着广泛的应用,例如:

  • 网页浏览历史记录管理: 浏览器使用双向循环队列来存储用户的浏览历史记录,以便用户可以轻松地在历史记录中前进或后退。
  • 消息队列: 消息队列使用双向循环队列来存储待处理的消息,以便消息生产者和消费者可以高效地进行消息通信。
  • 游戏中的回合管理: 游戏中,双向循环队列可以用来管理玩家的回合顺序,确保回合制游戏的正常进行。

总结:双向循环队列的价值与展望

双向循环队列作为一种高效的数据结构,在计算机科学和现实世界中都有着广泛的应用。通过本文的学习,相信您已经对双向循环队列有了更深入的了解,并能够将其运用到自己的项目中。未来,随着编程技术的发展,双向循环队列还将发挥出更大的价值,助力我们构建更加复杂的软件系统。