且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

队列中的循环数组

更新时间:2022-12-13 21:42:30

嗯,通常你跟踪第一个元素的索引以及当前的大小。如果大小等于数组的大小,则表示数组已满。启动一个新项目然后需要你增加数组。否则,你只需写入元素(start + size + 1)%array_size



当你出现一个元素,您只需将元素 start ,将其覆盖为空,以允许垃圾回收,减少大小,并增加开始,如有必要,将其换成0。



code>开始和大小是跟踪开始 next - 其中 next 是要排入队列的下一个元素的索引。当 start == next 时,您会发现数组是否满。然后排队(当不满时)只需要更改下一个,并且出队只需要更改 start 。如前所述,当您递增或递减开始 / 下一个时,您需要换行。


How is mod used to determine the beginning and end of a circular array in a queue?

Well, usually you keep track of the index of the first element, and the current size. If the size is equal to the size of the array, that means the array is full. Enqueuing a new item then requires you to grow the array. Otherwise, you just write to element (start + size + 1) % array_size.

When you dequeue an element, you just take the element at start, overwrite it with null to allow for garbage collection, decrement size, and increment start, wrapping to 0 if necessary.

An alternative to keeping track of start and size is to keep track of start and next - where next is the index of the next element to be enqueued. You spot if the array is full when start == next. Then enqueuing (when not full) only requires you to change next, and dequeuing only requires you to change start. As before, you need to wrap when you increment or decrement start/next.