# Understanding basic queue and dequeue operations

CLRS gives the following implementation for a queue's enqueue and dequeue operations

head = 1
tail = 1

ENQUEUE(Q, x)
Q[Q.tail] = x
if Q.tail == Q.length
Q.tail = 1
else Q.tail = Q.tail + 1

DEQUEUE(Q)
return x


but I'm having trouble understanding why both

if Q.tail == Q.length
Q.tail = 1


and

if Q.head == Q.length


are needed. What would be a conceptual (or possibly visual) explanation of these two if-statements?

• I think it's so because we "wrap" around when we are at the end of the queue. When we can't insert or delete at the last position, we move to the first position. – Gokul Nov 4 '18 at 16:12
• Check this too. – Gokul Nov 4 '18 at 16:28
• @Gokul Make an answer? (Buzzword: circular array/buffer) – Raphael Nov 4 '18 at 18:36

CLRS defines a queue using an array which wraps around i.e when we no longer can insert/delete in the last position, we move to the first position.

From the book,

The elements in the queue are in locations head[Q], head [Q] + 1, . . . , tail [Q] - 1, where we "wrap around" in the sense that location 1 immediately follows location n in a circular order.

Thus,

if Q.tail == Q.length

This is for the condition when the tail points to the last element.