【发布时间】: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