This is really interesting, because our instructor taught us this yesterday, and he could not understand it himself. Thus, we seemed to be hanging over this, not knowing the actual reason.
Here is the implementation of the Queue array in the famous book (which I donβt have, but what my instructor said. The author is very famous):
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 is "+ 1"? Why does it allocate one additional block of memory?
source share