简体   繁体   English

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

[英]Infinite while-loop while printing nodes in linkedlist

If I call createnode(x) in main and then follow that with printNodes();如果我在 main 中调用 createnode(x),然后使用 printNodes(); I will get an infinite while-loop that seems to be printing some memory address.我将得到一个似乎正在打印一些 memory 地址的无限 while 循环。 I am guessing the issue lies in the fact that i set head = temp?我猜问题在于我设置了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;

should be应该

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

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

head = temp;

which is a very complicate way of writing这是一种非常复杂的写作方式

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

Without this fix, printNodes results in undefined behaviour as a result of the lack of initialization of temp->next .如果没有这个修复, printNodes会由于 temp- temp->next的初始化不足而导致未定义的行为。

I don't see anything wrong with this code.我看不出这段代码有什么问题。 I copied your code and tried calling the createNode function followed by printNodes() and it gave me the correct output.我复制了您的代码并尝试调用 createNode function,然后调用 printNodes(),它给了我正确的 output。

#include <stdio.h>
#include <stdlib.h>

typedef struct x {
    int data;
    struct x* next;
}SinglyLinkedList;


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;
    }

}

int main() {
    createNode(7);
    printNodes();
    return 0;
}

Output: 7 Output: 7
I don't know why you're getting an infinite loop.我不知道你为什么会陷入无限循环。 A suggestion would be to also set temp->next = NULL in your createNode function after temp->data = data一个建议是在 temp- temp->data = data之后在你的 createNode function 中设置temp->next = NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM