#define SIZE 5
struct queue{ float data[SIZE];
int head,tail;
};
void init(struct queue *q){ q->head=0; q->tail=SIZE-1; }
int empty(struct queue *q){
int temp=q->tail+1;
if(temp==SIZE) temp=0;
return temp==q->head;
}
int full(struct queue *q){
int temp=q->tail+2;
//if(temp==SIZE) temp=0;
//if(temp==SIZE+1) temp=1;
if(temp>=SIZE) temp-=SIZE;
return temp==q->head;
}
void enqueue(struct queue *q, float item){
if(++q->tail>=SIZE) q->tail-=SIZE;
q->data[q->tail]=item;
}
float dequeue(struct queue *q){
float temp= q->data[q->head];
if(++q->head>=SIZE) q->head-=SIZE;
return temp;
}
上面的代码是我的教授给出的,我在理解部分if(++q->tail>=SIZE) q->tail-=SIZE;
排队函数和取消排队函数时遇到问题 if(++q->head>=SIZE) q->head-=SIZE;
为什么我需要评估这些条件? 有人请详细向我解释...谢谢
我举个例子:
看这张图片 :排队图像(由于声誉点,我无法在此处发布图片,所以,提供链接)
现在在图1中:
头部=0,尾部=3
所以,首先我们需要检查是否 tail==size-1
.但图 1 并非如此,因此,我们只需要增加尾部并在该位置存储新项目。
在图 2 中:
头部=2,尾部=7
所以,首先我们需要检查是否tail==size-1
.因此,我们将递增尾巴,然后从中减去size
以获得tail=0
。
总结此步骤,我们需要递增tail
并检查tail==size-1
,如果这是真的,我们需要做tail=tail-size
。因此,您的代码所做的是将步骤递增和检查结合起来。因此,它使用 size
按语句 ++q->tail>=size
检查 tail
的递增值。如果为真,则从tail
中减去size
。
在这里,无论条件是真是还是假,++q->tail
都会发生。
以防万一如果你不熟悉 C 语言,你可以在 enquque 中选择这个替代方案:
++q->tail; // or q->tail=q->tail+1 or q->tail+=1;
if(q->tail==size)
q->tail=q->tail-size;
q->data[q->tail]=item;
对于带头的取消排队也可以解释。
此方法也可以应用于其他问题。
你应该拥有的拳头或了解代码应该做什么。
在这个特定问题中,我们正在处理循环队列,这意味着有些东西(数字)站在一个有限的队列中,第一个离开的人在它的头部,最后一个到达
因为头部和尾部的"等待点"在不断变化,而队列的最大大小保持不变。这个想法是,您不会移动队列中的项目(就像队列中的人一样),您只需标记该队列中的第一个和最后一个项目并保持顺序
要正确理解这些陈述的内容,您应该首先尝试展开复合语句。
if(++q->tail>=SIZE) q->tail-=SIZE;
根据此表这意味着:
++q->tail /* we have a new arrival, tail is always the index of the last to come-in*/
/* lets say that the previous arrival was placed in q->data[4], the last element of the array, where we should put the new one? q->tail is now 5 but data[5] is out of bounds */
if((q->tail) >= SIZE) /* we increased the index but we have limited space in the array*/
/* this is the "circular" part. for size=5 it means that tail
was over the limit and should do the circle back to 0 to
make space for the new arrival */
q->tail -= SIZE;
试着自己绕着排队。使用优先规则将语句解压缩为多个语句。
是循环的。当您尝试将项目排队时
void enqueue(struct queue *q, float item){
if(++q->tail>=SIZE) q->tail-=SIZE;
q->data[q->tail]=item;
}
并且队列的尾部将到达 SIZEth 元素(索引处的理论元素超过队列末尾的一个),队列旨在从队列的开头包装和覆盖项目。