This is really interesting because our instructor was teaching this to us yesterday and he couldn't figure it out himself. So, we're kinda left hanging on this without knowing the actual reason why.
Here is the array implementation of a Queue in a famous book (which I don't have, but that's what my instructor said. The author is very reputed):
class QUEUE {
private:
int* q;
int N;
int head;
int tail;
public:
QUEUE(int maxN) {
q = new int[maxN + 1];
N = maxN + 1; head = N; tail = 0;
}
int empty() const {
return head % N == tail;
}
void put(int item) {
q[tail++] = item; tail = tail % N;
}
int get() {
head = head % N; return q[head++];
}
};
Inside the constructor, you see q = new int[maxN + 1];
. But why the '+ 1' ? Why is he allocating one extra int block of memory?
We need to give the size of the array because the complier needs to allocate space in the memory which is not possible without knowing the size. Compiler determines the size required for an array with the help of the number of elements of an array and the size of the data type present in the array.
Doubling reduces the cost to linear time.
Declaring Arrays: The array is indexed from 0 to size-1. The size (in brackets) must be an integer literal or a constant variable. The compiler uses the size to determine how much space to allocate (i.e. how many bytes).
If you try to access the array position (index) greater than its size, the program gets compiled successfully but, at the time of execution it generates an ArrayIndexOutOfBoundsException exception.
The problem that adding one to maxN
solves is that if you allocate exactly maxN
items, you would not be able to distinguish these two situations:
maxN
items.In both these situations head
and tail
would be equal to each other modulo N
.
Note: the implementation is not ideal, because inserting maxN+1
-th element wraps the queue around, so it becomes empty again. This shortcoming can be addressed in three ways:
bool
, ignore insertions that overflow the queue, and return false
if an insertion is ignored, orIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With