Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

java - Circular Arrays in Queues

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...