Circular Arrays in Queues

跟風遠走 提交于 2019-12-12 02:39:31

问题


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


回答1:


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.




回答2:


In a circular array the rear of queue is (front + number_of_elements_in_queue - 1) mod size_of_queue and front of the queue should be tracked after each dequeue.



来源:https://stackoverflow.com/questions/4002797/circular-arrays-in-queues

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