我正在研究C语言中的动态列表,这是我使用结构和指针创建的队列,它通常在排队节点,但是当我按此顺序调用Dequeue和Show方法时,它进入循环并显示奇怪的随机数。
struct Node { int data; struct Node *next; }; typedef struct Node node; int size = 0; node* front = NULL; node* rear = NULL;
//adds a new node at the end of the list void Enqueue(int n){
node *new_node = (node*)malloc(sizeof(node)); new_node->data = n; new_node->next = NULL; if (front == NULL && rear == NULL){ front = new_node; rear = new_node; return; } rear->next = new_node; rear = new_node; }
//when calling this method before show(), the loop issue occurs void Dequeue(){
node *tmp = front; if (front == rear){ front = rear = NULL; } else { front = front->next; } free(front); } //if just calling Enqueue() and Show() methods, it runs normally void Show(){ node *tmp = front; while(tmp != NULL){ printf("%d \n", tmp->data); tmp = tmp->next; } } int main(void){ Enqueue(1); Enqueue(2); Enqueue(3); Dequeue(); Show(); system("pause"); return 0; }
答案 0 :(得分:1)
检查您的Dequeue(...)
功能。重新分配后,您将释放前面的节点。试试这个
void Dequeue(){
node *tmp = front;
if (front == rear){
front = rear = NULL;
}
else {
front = front->next;
}
free(tmp);
}
答案 1 :(得分:1)
free(front); // SHOULD BE `free(tmp)`
正确的代码
void Dequeue(){
node *tmp = front;
if (front == rear)
front = rear = NULL;
else
front = front->next;
free(tmp);
}
答案 2 :(得分:0)
free(front);
我想你是说:
free(tmp);
在调用free()
之前,您需要重新分配front
指向新的队列头,因此释放该节点不是您想要的。 tmp
是指向原始头节点的指针的副本,在重新分配front
之后,可以安全地释放该指针。