622. 设计循环队列

48 阅读1分钟

622. 设计循环队列

解题思路

  • 通过内部的数组模拟队列的存储
  • 通过三个指针分表表示队首/队尾/下一个插入的下标. 从而控制数组的更新与值的获取

代码

class MyCircularQueue {
  _queue = [];
  _head = 0;
  _tail = 0;
  _insert = 0; // 下一个插入的下标
  _len = 0;
  _max = 0;

  constructor(k) {
    this._max = k;
  }

  enQueue(value) {
    if (this.isFull()) return false;
    this._queue[this._insert] = value;
    this._tail = this._insert;
    this._insert++;
    if (this._insert >= this._max) this._insert = 0;
    this._len++;
    return true;
  }

  deQueue() {
    if (this.isEmpty()) return false;
    this._head++;
    if (this._head >= this._max) this._head = 0;
    this._len--;
    return true;
  }

  Front() {
    return this.isEmpty() ? -1 : this._queue[this._head];
  }

  Rear() {
    return this.isEmpty() ? -1 : this._queue[this._tail];
  }

  isFull() {
    return this._len >= this._max;
  }

  isEmpty() {
    return this._len <= 0;
  }
}