How to make a circular buffer?

我与影子孤独终老i 提交于 2021-01-29 18:06:15

问题


I have to make a circular buffer out of an array for class and I can't quite grasp how the concept is implemented. I get that there are are indexes that go back and forth but I don't really understand how this is actually implemented. How do you even assign a tail or head to elements of an array, or index them both ways? Any advice, code or explanation would be extremely helpful.


回答1:


A circular buffer is basically just an array and two integers that keep track of the positions that you consider to be the "tail" and the "head".

The empty buffer starts out with both "tail" and "head" at the same index (0 is as good a choice as any).

When you add to the buffer, you insert at where the "tail" points add, and then move the tail to next position. It gets "circular" because when the "tail" falls off the end of the array, it jumps back to its beginning (index 0).

Similarly, you remove from the buffer from either head or tail end by looking at and adjusting the respective positions.




回答2:


You make something circular by connecting the tail of the structure to its head. In an array this can be done in a number of different ways (Iterator, custom class/handler, etc.) but what they all have in common is the next element after the tail is the head.

Here is a very simple example using the % operator to handle the tail to head 'connection':

int[] ary = {0, 3, 5};

for(int i = 0; i < 100; i++) {
    System.out.println(ary[i % 3]);
}

this loop will output: 0 3 5 0 3 5 0 3 5......for 100 iterations



来源:https://stackoverflow.com/questions/26111676/how-to-make-a-circular-buffer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!