How is mod used to determine the beginning and end of a circular array in a queue?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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, decrementsize, and incrementstart, wrapping to 0 if necessary.An alternative to keeping track of
startandsizeis to keep track ofstartandnext– wherenextis the index of the next element to be enqueued. You spot if the array is full whenstart == next. Then enqueuing (when not full) only requires you to changenext, and dequeuing only requires you to changestart. As before, you need to wrap when you increment or decrementstart/next.