The title

Train of thought

  • Use arrays.
  • The following things can happen

  • So, head can be anywhere.
  • TailIndex = (headIndex + count − 1) mod Capacity

code

TailIndex = (headIndex + count − 1) mod capacity
class MyCircularQueue {
  private int[] queue; / / array
  private int headIndex; / / the first index
  private int count; // The number of elements in the current queue
  private int capacity; // The maximum capacity of the queue

  / / initialization
  public MyCircularQueue(int k) {
    this.capacity = k;
    this.queue = new int[k];
    this.headIndex = 0;// The queue head is 0
    this.count = 0;
  }

  // Insert an element, return true on success
  public boolean enQueue(int value) {
    if (this.count == this.capacity)
      return false;
    this.queue[(this.headIndex + this.count) % this.capacity] = value;// The last position in the queue
    this.count += 1;
    return true;
  }

  // Remove an element, return true on success
  public boolean deQueue(a) {
    if (this.count == 0)
      return false;
    this.headIndex = (this.headIndex + 1) % this.capacity;
    this.count -= 1;
    return true;
  }

  // return the first element of the queue
  public int Front(a) {
    if (this.count == 0)
      return -1;
    return this.queue[this.headIndex];
  }

  // return the last element of the queue
  public int Rear(a) {
    if (this.count == 0)
      return -1;
    int tailIndex = (this.headIndex + this.count - 1) % this.capacity;
    return this.queue[tailIndex];
  }

  // Check whether the queue is empty
  public boolean isEmpty(a) {
    return (this.count == 0);
  }

  // Check if the queue is full
  public boolean isFull(a) {
    return (this.count == this.capacity); }}Copy the code