C 循环排队问题

C 循环排队问题,c,queue,C,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

我在从书上学习排队。我在学习循环队列时遇到了一个问题。我正在学习的作者使用下面的代码来解释如何在循环队列中插入元素

#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 */
}

我的代码正确吗?

作者的实现没有错误,而且是故意的,但除非您考虑/查看出列过程,否则您不会看到它。问题是如何确定队列是否为空

spos==rpos
时,队列为空。如果您在
spos+1==rpos
时不说队列已满,但
spos==rpos
则无法区分满队列和空队列


您是正确的,但是注意到您将保留一个队列条目。您的队列将只容纳99个项目,而不是100个。“缺失”是您需要在不使用RPO、SPO和队列之外的任何其他变量的情况下区分完整循环队列和空循环队列所付出的代价。

您可能会说,您引用的是哪本书/作者?C:完整参考,Ed Herbert Schildties第四版您的代码是错误的。它会增加SPO两次,所以你只能在p中每隔一个条目使用一次。哦!那是无意中犯的错误。我编辑了这段代码。之前没有其他检查,当我后来添加它时,我一定忘了删除之前的语句。如果我在If-else块之前删除额外的增量,我的代码是否正确?我想不是,我可能需要考虑空队列,并且我可能在查找空队列的检查时遇到问题。避免浪费队列槽的方法的一个很好的变化是将队列大小设为2的幂,并将读/写索引设为2的更大幂。在这种情况下,无需额外存储(除非队列大小为256或65536个元素),就可以轻松区分队列已满和队列已空的情况。在C语言中,实现这一点的最简单方法是将索引简单地设置为无符号整数类型,并让它们随时换行。
#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;

}