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)
- 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;
}
- 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 ];
}
- 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
CodePudding user response:
- 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.
read
is adjusted after becauserear
is the place where the new element is supposed to be added. After the element is added, it is incremented. Andfront
is the index where the element is supposed to be popped out, because it alread has the element.- Remember the max no of items is
data.length - 1
sofront - rear
has to equal1
if the queue is supposed to be full.
I hope this answers your question. Feel free to ask questions in the comments.