Search code examples
arraysqueuecircular-buffer

Circular buffers (start value gets removed, what happens?)


I'm trying to get my head around Circular/ring buffers and I'm a little stuck on a question.

If I have a linear queue such as the following:

66,    20,      30,      40,      19,      empty slot
0         1         2         3         4         5

Front: 0 (being 66), back: 5, length: 5

If a value gets removed (considering 0 was the first to get added, I believe 0 (which is 66), would be removed.

My question: Would 20 become the first in the queue then? And how would the layout be after that? Would anything move, e.g. indexes/pointers, or anything of that nature?

Thanks.


Solution

  • Yes. You'd have something similar to the below:

    __   20   30   40   19   __
    0    1    2    3    4    5
    

    Front: 1, back: 5, length: 4

    Notice that you could even have left the '66' in the position 0 (no need to "erase" it), which is what most implementations do. The first item in the queue is the one pointed by the "front" index, not necessarily the first item in the array which is backing the queue.