Stacks and queues · Exercise 64 of 100

Circular queue

A circular queue keeps a front index for removals and a next-write index for insertions in a fixed array. Each index wraps to zero when it moves past the last slot, so later arrivals can reuse freed slots. Keep a count and allow a removal only when the count is positive and an insertion only when there is room.

Try it yourself

An empty circular queue has slots numbered 0 through 3 and starts writing at slot 0. Enqueue packets 4, 7 and 9, dequeue twice, then enqueue packets 6 and 8. In which slot is packet 8 written?

One-step hint

Track the next write slot separately from the read slot. Advance the write marker only on an enqueue, wrapping after the last slot.

Worked solution
  1. Packets 4, 7 and 9 fill slots 0, 1 and 2. Removing 4 and 7 frees the first two slots while the next-write index stays at 3.
  2. Packet 6 goes into slot 3. The next-write index wraps to 0, so packet 8 goes into slot 0.
DSA compiler