622. 设计循环队列

402 阅读1分钟

题目

image.png

思路

  • 使用数组实现。
  • 可能会出现下列情况

image.png

  • 所以,head可能出现在任何位置。
  • 获取队尾的inedx:tailIndex = (headIndex + count − 1) mod capacity

代码

// 获取队尾的inedx:tailIndex = (headIndex + count − 1) mod capacity
class MyCircularQueue {
  private int[] queue; //数组
  private int headIndex; //队首index
  private int count; //当前队列中元素的个数
  private int capacity; //队列的最大容量

  //初始化
  public MyCircularQueue(int k) {
    this.capacity = k;
    this.queue = new int[k];
    this.headIndex = 0;//一开始队首为0
    this.count = 0;
  }

  //插入一个元素,成功返回true
  public boolean enQueue(int value) {
    if (this.count == this.capacity)
      return false;
    this.queue[(this.headIndex + this.count) % this.capacity] = value;//队尾的后一个位置
    this.count += 1;
    return true;
  }

  //移除一个元素,成功返回true
  public boolean deQueue() {
    if (this.count == 0)
      return false;
    this.headIndex = (this.headIndex + 1) % this.capacity;
    this.count -= 1;
    return true;
  }

  //返回队首元素
  public int Front() {
    if (this.count == 0)
      return -1;
    return this.queue[this.headIndex];
  }

  //返回队尾元素
  public int Rear() {
    if (this.count == 0)
      return -1;
    int tailIndex = (this.headIndex + this.count - 1) % this.capacity;
    return this.queue[tailIndex];
  }

  //检查队列是否为空
  public boolean isEmpty() {
    return (this.count == 0);
  }

  //检查队列是否满了
  public boolean isFull() {
    return (this.count == this.capacity);
  }
}