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;
At the end of first call to push(1) ; queueFront = 0 , queueBack = 1 , 1 gets added to inputArray[1] rather than 0;
At the end of second call to push(2), queueFront = 0, queueBack = 2, , 2 gets added to inputArray[2],
Now , (queueBack + 1) % arrayLength == queueFront is true, whereas there is one more empty space left i.e., inputArray[0] .
Thanks
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With