我需要在 C 中为家庭作业项目的一小部分实现一个队列。几年来我一直在用各种语言做这件事,所以我很惊讶我遇到了这么多麻烦。我的问题是 Head 的值不断更改为最近的附加值。
到目前为止,这是我的代码:
void Enqueue( fifo* queue, int customerData)
{
//Determine if a head or tail exists
int tailExists = 0;
if(queue->tail->customerId >= 0){
tailExists = 1;
}
//Create new elements
struct fifo_element a, *element;
element = &a;
if(tailExists == 1)
printf("test2 the head is %d\t", queue->head->customerId);
element->customerId = customerData;
if(tailExists == 1)
printf("test3 the head is %d\t", queue->head->customerId);
//Set the next element to the current tail
if(tailExists == 1)
element->next = queue->tail;
else
element->next = NULL;
//Set the prev element to null
element->prev = NULL;
//Set the last element's previous to the new element
if(tailExists == 1){
queue->tail->prev = element;
}
//Set the tail to the new element
queue->tail = element;
if(tailExists == 0){
queue->head = element;
}
printf("the head is %d\t", queue->head->customerId);
printf("the tail is %d\t", queue->tail->customerId);
}
根据 printf 行,该行element->customerId = customerData;
导致 Head 值发生变化。但是,我不明白这怎么可能……为什么会这样?
(我的测试程序只是从 0->4 运行一个 for 循环,使用 customerData 值 i 调用 enqueue)。