在链表中打印节点时无限循环

Infinite while-loop while printing nodes in linkedlist

如果我在 main 中调用 createnode(x),然后在其后调用 printNodes();我将得到一个似乎正在打印一些内存地址的无限 while 循环。我猜问题在于我设置了 head = temp?

SinglyLinkedList *head = NULL;

void createNode(int data){
    SinglyLinkedList *temp = malloc(sizeof(SinglyLinkedList));
    temp-> data = data;

    if(head == NULL){
        head = temp;
        return;
    }

    temp->next = head;
    head = temp;
}

void printNodes(){

    SinglyLinkedList *temp = head;

    while ( temp != NULL ){
        printf("%d\r\n",temp->data);
        temp = temp->next;
    }

}
SinglyLinkedList *temp = malloc(sizeof(SinglyLinkedList));
temp->data = data;

if(head == NULL){
    head = temp;
    return;
}

temp->next = head;
head = temp;

应该是

SinglyLinkedList *temp = malloc(sizeof(SinglyLinkedList));
temp->data = data;
temp->next = head;    // Moved

if(head == NULL){
    head = temp;
    return;
}

head = temp;

这是一种非常复杂的写法

SinglyLinkedList *temp = malloc(sizeof(SinglyLinkedList));
temp->data = data;
temp->next = head;
head = temp;

如果没有此修复,printNodes 会由于缺少 temp->next 的初始化而导致未定义的行为。