Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtle bugs in implementing circular queue

Tags:

c

queue

i am trying to implement a simple circular queue operation as below

void push(int theElement)
{
  //Check if the push causes queue to overflow
    if  (((queueBack + 1 ) % arrayLength) == queueFront) {
       std::cout<<"Queue is full."<<std::endl;
       return ;
    } 
    queueBack = (queueBack + 1) % arrayLength;
    inputArray[queueBack] = theElement;
}

int pop()
{
   //Check if queue  is already empty
  if ( queueFront == queueBack ) {
    std::cout<<"Queue is empty."<<std::endl;
    return;
  }
  queueFront = (queueFront + 1 ) % arrayLength;
  return inputArray[queueFront];

}

Considering initially queueFront = 0 and queueBack = 0, The above code results in a full queue even though actually it isn't. How do i correct this? Is my implementation correct in the first case?

Test cases Initially arrayLength = 3, queueFront = 0, queueBack = 0;

  1. At the end of first call to push(1) ; queueFront = 0 , queueBack = 1 , 1 gets added to inputArray[1] rather than 0;

  2. At the end of second call to push(2), queueFront = 0, queueBack = 2, , 2 gets added to inputArray[2],

  3. Now , (queueBack + 1) % arrayLength == queueFront is true, whereas there is one more empty space left i.e., inputArray[0] .

Thanks

like image 839
Abhay Hegde Avatar asked Jul 06 '26 16:07

Abhay Hegde


1 Answers

It's not a bug, it's a feature of circular queues. If you don't leave one empty slot, then there's no way to distinguish between the full and empty cases. Of course, the pop function should return the int that it read from the queue, and there's no need to set the value to -1.

like image 149
user3386109 Avatar answered Jul 09 '26 00:07

user3386109