如何使用JavaScript实现高效的循环队列

51 min read

以下是用 JavaScript 实现循环队列的示例代码:

class CircularQueue {
  constructor(k) {
    this.queue = new Array(k);
    this.head = -1;     // 头部指针
    this.tail = -1;     // 尾部指针
    this.size = 0;      // 记录队列元素个数
    this.capacity = k;  // 记录队列容量
  }

  // 入队
  enqueue(val) {
    if (this.isFull()) {
      console.log("队列已满!");
      return false;
    } 
    if (this.isEmpty()) {
      this.head = 0;
    }
    this.tail = (this.tail + 1) % this.capacity;
    this.queue[this.tail] = val;
    this.size++;
    return true;
  }

  // 出队
  dequeue() {
    if (this.isEmpty()) {
      console.log("队列为空!");
      return false;
    }
    const val = this.queue[this.head];
    if (this.head === this.tail) {
      this.head = this.tail = -1;
    } else {
      this.head = (this.head + 1) % this.capacity;
    }
    this.size--;
    return val;
  }

  // 获取队首元素
  front() {
    if (this.isEmpty()) {
      console.log("队列为空!");
      return false;
    }
    return this.queue[this.head];
  }

  // 获取队尾元素
  rear() {
    if (this.isEmpty()) {
      console.log("队列为空!");
      return false;
    }
    return this.queue[this.tail];
  }

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

  // 判断队列是否已满
  isFull() {
    return this.size === this.capacity;
  }

  // 获取队列长度
  getLength() {
    return this.size;
  }
}

使用方法:

const queue = new CircularQueue(5);

queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
console.log(queue.enqueue(6));  // 队列已满!,输出 false
console.log(queue.getLength());  // 5
console.log(queue.front());  // 1
console.log(queue.rear());  // 5
console.log(queue.dequeue());  // 1
console.log(queue.front());  // 2

这里使用了一个数组,通过头部指针 head 和尾部指针 tail 来实现循环队列。当队列满了时,尾部指针指向数组的最后一个元素,此时再添加元素时就需要从头开始。可以使用取模运算来实现。