我有以下功能

void printLinkedList(struct node *head) {

    printf("%d-->", head->data);

    while(head->ptr != NULL) {
        head = head->ptr;
        printf("%d-->", head->data);
    }
    printf("NULL\n");
}


我想打印以下列方式构造的链表的内容:

for (int i = 0; i < 10; i++) {
    head->data = i+1;
    head->ptr = malloc(sizeof(struct node));
    head = head->ptr;
}


因此,理想情况下,这应该给我以下信息:

1-->2-->3-->4-->...-->10-->NULL


但是,如果一切正确,则valgrind会给我内存错误。请告诉我我在做什么错。

最佳答案

检查一下。

struct node *temp, *head= NULL, *last = NULL;
    for (int i = 0; i < 10; i++) {
        temp = malloc(sizeof(struct node));
        temp->data = i+1;
        temp->ptr = NULL;
        if (head == NULL)
          head = temp;
        if (last != NULL)
          last->ptr = temp;
        last = temp;
    }
printLinkedList(head);

关于c - 为什么此打印链接列表功能不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14949695/

10-11 22:05
查看更多