Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple queue algorithm

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:

Pastie.org

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;
    }
like image 888
Daniel Sorichetti Avatar asked May 23 '26 15:05

Daniel Sorichetti


1 Answers

The first check is performing the following part of the statement in the comments.

putloc is one less than getloc

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.

like image 138
Justin Niessner Avatar answered May 26 '26 04:05

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!