I am reading about implementation of DynaArrayQueue (queue that doubles in size when there are no enough elements)
I have certain questions regarding two methods in it.
Let capacity be the capacity of the queue.
getQueueSize() Method
public int getQueueSize()
{
if(front == -1) return 0;
//Here why can't the size by simply [(rear -front +1) %capacity ]
int size = (capacity - front + rear +1) % capacity;
if(size == 0) return capacity;
else return size;
}
When calculating the size why are we using
size = (capacity - front + rear +1 ) % capacity , instead of simply (rear - front +1) % capacity. ?
Question 2:
resizeQueue()
This is the method that resizes the queue
private void resizeQueue()
{
int initCapacity = capacity;
capacity *=2;
int[] oldArray = array;
array = new init[this.capacity];
//this is fine
for(int i=0; i<oldArray.length;i++)
{
array[i] =oldArray[i];
}
//why do we need this ?
if(rear < front)
{
for(int i =0 ; i<front ; i++)
{
array[i+initCapacity] = this.array[i];
array[i]= null;
}
rear = rear + initCapacity;
}
}
The first for loop in the method is straight forward, but why do we need the second if loop for ?. What conditions it is taking care of ?