为什么我的代码没有向这个链表中插入一个新节点?

Why does my code not insert a new node into this linked list?

我是编程新手。我只是想知道为什么这不起作用。 我对指针的理解不是很清楚,尤其是在跨函数使用指针的时候。

void append(struct Node** head_ref, float new_data)
{

    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

    struct Node *last = *head_ref;  /* used in step 5*/


    new_node->data  = new_data;
    new_node->next = NULL;

    while (last != NULL)
        last = last->next;


    last = new_node;
    return;
}

void append(struct Node** head_ref, float new_data)
{

while (last->next != NULL)
        last = last->next;


    last->next = new_node;
    return;
}

在第一个函数中没有包含新数据,我只得到原始链表。

但是第二个函数工作得很好。在链表开头插入新节点时,双指针如何工作? (看到了这个问题的答案,还是一头雾水)

在第一个示例中,您移动指针 last 直到它指向 NULL 位置。然后,您将指针设置为 new_node。但是,此时 last 与您的链表没有真正的关联。它只是指向一些内存的指针。在第二个例子中,正确的例子,你迭代直到到达链表的尾部,其中该节点的 nextNULL。然后,将 next 设置为 new_node。列表现在有一个新尾巴,即 new_node.

改变局部变量last不会改变前一个(最后)节点的数据成员next的值。

为了更清楚起见,我们假设列表是空的。那么你就得改变这个双指针所引用的指针head_ref。 您声明了一个新指针

struct Node *last = *head_ref;

循环

while (last != NULL)
    last = last->next;

被跳过,因为现在 last 等于 NULL 死于前面声明中的初始化。然后你改变了这个局部变量 last

last = new_node;

由于last*head_ref占用不同的内存,head_ref指向的指针的原始值没有改变。您更改了 last 占用的内存,但没有更改 head_ref.

占用的内存

另外你应该检查内存是否分配成功。

函数可以如下所示

int append( struct Node **head_ref, float new_data )
{
    struct Node *new_node = malloc( sizeof( struct Node ) );
    int success = new_node != NULL;

    if ( success )
    {
        new_node->data  = new_data;
        new_node->next  = NULL;

        while ( *head_ref != NULL ) head_ref = &( *head_ref )->next;

        *head_ref = new_node;
    }

    return success;
}

至于这个循环(我想你只想展示循环而不是整个函数)

while (last->next != NULL)
        last = last->next;


    last->next = new_node;

那么您正在更改前一个(最后一个)节点的数据成员next

如果最初 head_ref 等于 NULL,则此循环将不起作用。