Circular Queue Problem

I study the lines from the book. I had a problem while learning round robin. The author I'm learning from uses the following code snippet 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 load index; otherwise, there is room for another event in the queue.

SO acc. to the author, if spos (which contains the next free storage location index ) is 4 and rpos = 5, then the queue is full. Is that not so? Since spos = 3 means that the memory cell in 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?

+3
1

, , dequeue. , , ?

, spos == rpos. , , spos+1 == rpos, spos == rpos, .

, , . 99 , 100. "" - , , - , rpos, spos queue.

+6

Source: https://habr.com/ru/post/1760941/


All Articles