c - 打印链表中的节点时无限循环

标签 c linked-list

如果我在 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 初始化而导致未定义的行为。

关于c - 打印链表中的节点时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70677062/

相关文章:

使用 for 循环创建链表

c - C++ 链表中的成对交换

c - 在标准 C 中从头开始实现 memcpy 在技术上是不可能的吗?

c - 如何模拟边沿触发触发器?

c - 有没有需要很长时间的单行C库函数?

c - 链表交换期间未传递指针

c - 链表和指针的问题(C)

c - 如何在 alpine 上编译 32 位的 hello world?

c - 以下代码的时间复杂度

java - 通用双向链表