简体   繁体   中英

implementation of a queue using a circular array

I have found these algorithms in the internet but I can not understand that why in the enqueue method we compare size with N-1??? please help me thanks!!

Algorithm size():
return (N-f+r)mod N



Algorithm enqueue(e):
if size()=N-1 then
   throw a FullQueueException
Q[r]<---e
r<----(r+1)mod N

The reason that the queue is full when the size is N-1 is that in this simple implementation, 'r' represents the index of the next free element and 'f' represents the next element to retrieve. If 'f' and 'r' are equal, the queue is empty, so the queue is full if incrementing 'r' would result in it being equal to 'f'.

In this implementation, at least one element is always empty. This usually is more efficient than adding more logic to differentiate the case where the 'f' and 'r' is equal and the queue is full vs the case where it is empty.

BTW, in most processors the mod function is a lot more expensive than using logic like this:

Algorithm enqueue(e):
rNext<---r + 1
if rNext = N
    rNext<---0
if rNext = r then
    throw a FullQueueException
r<---rNext
Q[r]<---e

You provided a very broken (and incorrect) implementation.

That being said, a circular queue in an array usually starts at a given index and ends at another given index (thus the f and r). However, no matter what you do, you can't have more items in the queue than you do in the underlying array.

The size function here is supposed to calculate the number of elements in the queue. If the number becomes dangerously close to the total array size, then the queue is full.

I agree with @Matthew Flaschen's comment, but I will take a guess. I suspect that the queue is N long, and one element is reserved for a sentinel for searching. It is not how I would do it, though.

Given an implementation of circular queues wherein the begin and end are kept as indicies modulo the size of the allocated underlying array, say N, it is necessary that the actual capacity of the queue (not the array) be less than N, elsewise the begin and end indicies will be equal and there would be ambiguity between empty and full.

Thus, when the allocated underlying array is of size N the true capacity of the queue is N-1. That is the why of the test.

There are ways around this that actually allow use of all N slots AND eliminate the division implicit in taking the index modulo n.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM