我正在从一本书中学习队列。在学习循环队列时遇到了问题。我所学的作者使用以下代码片段来解释如何将元素插入循环队列。
#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 */
}
他进一步指出:当存储索引比检索索引小1时,队列已满;否则,队列中还有空间来容纳另一个事件。 因此,根据作者的说法,如果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;
}
我的代码正确吗?