实现一个循环队列,并设计一个验证循环队列是否为空或满的算法。

循环队列的实现

循环队列是一种环形数据结构,它允许在队列的两端进行添加和删除操作。下面是一个用JavaScript语言实现的循环队列的示例:

// 定义循环队列类

class MyCircularQueue {
  constructor(k) {
    this.queue = new Array(k + 1);
    this.front = 0;
    this.rear = 0;
    this.size = k + 1;
  }

  // 入队
  enQueue(value) {
    if (this.isFull()) {
      return false;
    }
    this.queue[this.rear] = value;
    this.rear = (this.rear + 1) % this.size;
    return true;
  }

  // 出队
  deQueue() {
    if (this.isEmpty()) {
      return false;
    }
    this.front = (this.front + 1) % this.size;
    return true;
  }

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

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

// 创建循环队列实例
let circularQueue = new MyCircularQueue(3);

// 入队
let result1 = circularQueue.enQueue(1); // 返回 true

// 出队
let result2 = circularQueue.deQueue(); // 返回 true

// 检查队列是否为空
let result3 = circularQueue.isEmpty(); // 返回 false