所以这是一个非常简单的程序来创建和显示一个链表。在这里,我陷入了显示循环,我在屏幕上看到了无限的“2->2->2->...”。
调试后,我可以看到我的程序总是进入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();
}