I'm learning queues from a book. I've got into a problem while learning circular queue. The author from which I'm learning uses the following piece of code to explain how an element is inserted in a circular queue.
#define MAX 100
char *p[MAX];
int spos = 0; // spos: holds the index of the **next free** storage location
int rpos = 0;// rpos: holds the index of the next item to retrieve
void qstore(char *q)
{
/* The queue is full if either spos is one less than rpos
or if spos is at the end of the queue array and rpos
is at the beginning.
*/
if(spos+1= =rpos || (spos+1==MAX && !rpos)) <-- /***Problem is here**. Is it even
correct?*/
{
printf(''List Full\n");
return;
}
p[spos] = q;
spos++;
if(spos==MAX)
spos = 0; /* loop back */
}
He further states that: The queue is full when the store index is one less than the retrieve index; otherwise, there is room in the queue for another event.
SO, acc. to the author, if spos (which holds the index of the next free storage location) is equal to 4 and rpos=5, then the queue is full. Isn't this incorrect? Because spos=3 means that the memory location at p[3] is empty.
So I decided to change the program.
#define MAX 100
char *p[MAX];
int spos = 0; // spos: holds the index of the **last allocated** storage location
int rpos = 0;// rpos: holds the index of the next item to retrieve
void qstore(char *q)
{
/* The condition for queue full is same as the previous program*/
/* The queue is full if either spos is one less than rpos
or if spos is at the end of the queue array and rpos
is at the beginning.
*/
if((spos+1==rpos) || (spos+1==MAX && rpos==0)) // Also changed syntax of test condition.
{
printf("Queue Full\n");
}
spos++
if((spos+1==MAX) && (rpos!=0))
{
spos=0;
}
else
{
spos++;
}
p[spos]=q;
}
Is my code correct?