0

我有以下功能

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 会给我内存错误。请告诉我我做错了什么。

4

4 回答 4

1

检查这个。

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);
于 2013-02-19T04:20:03.023 回答
1

我稍微修改了汤姆斯的答案:

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

由于 temp 未正确分配,原始代码会产生段错误。

于 2013-02-19T04:46:09.350 回答
0

如果在不构造链表的情况下调用 print 函数,会报错,所以修改 print 函数如下:

void printLinkedList(struct node *head) 
{
    while(head != NULL) 
    {
        printf("%d-->", head->data);
        head = head->ptr;
    }
    printf("NULL\n");
 }
于 2013-02-19T05:05:26.330 回答
0

这是修改后的代码-您的构造有问题。

typedef struct _node {
    int data;
    struct _node *ptr;
} NODE, *PNODE;

PNODE head;

int main (int argc, char * argv[])
{

    head = (PNODE) malloc(sizeof(NODE));
    PNODE node = head;

    int i = 0;
    node->data = ++i;
    node->ptr = NULL;

    for ( ;i < 10; ) {
        PNODE tmp = (PNODE) malloc(sizeof(NODE));
        tmp->data = ++i;
        tmp->ptr = NULL;

        node->ptr = tmp;
        node =tmp;
    }

    printLinkedList(head);

    freeLinkedList(head);

    return 0;

}
于 2013-02-19T06:56:34.387 回答