【问题标题】:Circular queue problem循环队列问题
【发布时间】:2011-04-02 04:23:54
【问题描述】:

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

#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(保存下一个空闲存储位置的索引)等于 4 且 rpos=5,则队列已满。这不正确吗?因为 spos=3 表示 p[3] 处的内存位置为空。


所以我决定改变程序。

#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;

}

我的代码正确吗?

【问题讨论】:

  • 您能说一下,这是您引用的哪本书/作者吗?
  • C: The Complete Reference, 4th by Ed Herbert Schildt

标签: c queue


【解决方案1】:

作者的实现没有错,是故意的,但除非你考虑/看到出列过程,否则你不会看到它。问题是如何判断队列是否为空?

spos == rpos 时队列为空。如果spos+1 == rpos 时您没有说队列已满,但spos == rpos 您已经失去了区分满队列和空队列的能力。

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

【讨论】:

  • 是的,您的代码是错误的。它会增加 spos 两次,因此您只会使用 p 中的所有其他条目。
  • 哦!这是一个无意的错误。我编辑了这段代码。之前没有else检查,后来添加时,我一定忘记删除以前的语句。如果我在 if-else 块之前删除那个额外的增量,我的代码是否正确?我猜不是,我可能需要考虑空值,而且我在查找空队列检查时可能会遇到问题。
  • 避免浪费队列槽的方法的一个很好的变体是使队列大小为 2 的幂,并使读/写索引以更大的 2 的幂换行。在这种情况下,无需额外存储即可轻松区分队列满和队列空情况(除非队列大小为 256 或 65,536 个元素)。在 C 中,最简单的方法是让索引简单地为无符号整数类型,并让它们在需要时进行包装。
猜你喜欢
  • 2022-01-12
  • 2012-07-06
  • 1970-01-01
  • 2018-07-12
  • 2012-08-05
  • 1970-01-01
  • 2014-01-04
  • 1970-01-01
  • 2011-07-17
相关资源
最近更新 更多