简体   繁体   中英

Circular Queue Implementation in Java

I was reading a queue implementation that I stumbled upon in Github and was having difficulty understanding why certain behaviors were used. (The link to the repository could be found here )

  1. The code adds 1 to the initial capacity that the user expects the queue size to be declared with. The owner explains that this is because the initial maximum size is data.length - 1, but does not explain why. Here is that section of the code:
public ArrayQueue(int capacity) {
  // ArrayQueue maximum size is data.length - 1.
  data = new Object[capacity + 1];
  front = 0;
  rear = 0;
}
  1. I am not sure why the rear index is adjusted after the item has already been inserted in the queue within the offer function, yet the head index is adjusted prior in poll. Does it make a difference?
public void offer(T elem) {
    if (isFull()) {
      throw new RuntimeException("Queue is full");
    }
    data[rear++] = elem;
    rear = adjustIndex(rear, data.length);
 }
public T poll() {
    if (isEmpty()) {
      throw new RuntimeException("Queue is empty");
    }
    front = adjustIndex(front, data.length);
    return (T) data[front++];
}
  1. Why do we need to add data.length to (front - rear) to check if list is full?
  public boolean isFull() {
    return (front + data.length - rear) % data.length == 1;
  }

Thank you

  1. He has mentioned it above

ArrayQueue maximum size is data.length - 1. The place of the variable rear is always in front of the variable front logistically if regard the data array as circular. so the number of states of the combination of rear and front is the length of the data array. And one of the total states is used to be the judge if the queue is empty or full.

  1. read is adjusted after because rear is the place where the new element is supposed to be added. After the element is added, it is incremented. And front is the index where the element is supposed to be popped out, because it alread has the element.
  2. Remember the max no of items is data.length - 1 so front - rear has to equal 1 if the queue is supposed to be full.

I hope this answers your question. Feel free to ask questions in the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM