所以这是一个非常简单的程序来创建和显示链表。在这里,我陷入了显示循环中,并且在屏幕上看到了无限的“2-> 2-> 2 - > ...”。调试C链接列表程序陷入无限循环
调试后,我可以看到我的程序总是进入if
语句insertNode()
,而它应该只在那里一次,即当链表被初始化时。
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * next;
};
struct node * head = NULL;
struct node * curr = NULL;
void insertNode(struct node * temp2) {
if (head == NULL) {
head = temp2;
head->next = NULL;
}
else {
temp2->next = head;
head = temp2;
}
}
void display() {
curr = head;
while (curr->next != NULL)
{
printf("%d->",curr->data);
curr = curr->next;
}
}
void main() {
struct node * temp = (struct node *) malloc (sizeof(struct node));
temp->data = 5;
insertNode(temp);
temp->data = 6;
insertNode(temp);
temp->data = 1;
insertNode(temp);
temp->data = 2;
insertNode(temp);
display();
}
如果您在显示屏内移动'curr',而不是污染全球区域,那么如果您仅在该区域内使用它,则会更好。尽量避免使用全局变量。 –
也会检查'display',这样'head'在取消引用前真正指向某个东西。 –