data-structurescircular-queue

Explanation for the following expected circular queue result


I'm trying to create a circular queue and come across this problem.enter image description here

As you see, my answer is incorrect. I still don't understand the reason why it is the case, so let's go through everything again.

  1. Create a circular queue of size 2
  2. Enqueue 8, current queue: 8
  3. Enqueue 8, current queue: 8, 8
  4. Front: 8 (no change to the queue)
  5. Enqueue 4, current queue: 4, 8
  6. Dequeue, current queue: 8
  7. Enqueue 1, current queue: 8, 1
  8. Enqueue 1, current queue: 1, 1
  9. Rear: 1 (no change to the queue)
  10. Is empty: false (no change to the queue)
  11. Front : 1 (no change to the queue)
  12. Dequeue, current queue: 1

Following my analysis, the last Front operation should return 1 as the queue is 1, 1. However, the answer is 8 instead. Did I miss something? Please explain this for me.


Solution

  • Figured it out. It is required to check whether a queue is full before enqueueing. However, I didn't do so as I thought that circular queue is a form of infinite DS like drop-out stack so my answer is wrong.