This is not a request for a queueing algorithm, I know there are plenty.
I’m reading a C# book and it explains the Circular Queue algorithm with a code example. On lines 13, 14 and 15, he explains how to check if the queue is full. However I can’t understand why the first optional condition is necessary. Could someone show me a situation where it will be needed?
Here’s the class code:
And my question is about this section: (putloc + 1 == getloc)
public bool Put(char ch) {
/* Queue is full if either putloc is one less than
getloc, or if putloc is at the end of the array
and getloc is at the beginning. */
if (putloc + 1 == getloc || ((putloc == q.Length - 1) && (getloc == 0)))
{
return false;
}
The first check is performing the following part of the statement in the comments.
This check is needed because your Queue is circular. If you could always assume the end of the Queue was the last element in the Array, then the check would not be needed. In this case though…the end of the Queue could happen in the middle of the Array in which case the Queue would be full and you hit this condition.