开发者

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 compa开发者_StackOverflow中文版re 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


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 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜