当我在循环中调用函数时,将新节点插入单链列表不起作用

问题描述 投票:0回答:2

我正在尝试将一个节点追加到列表的末尾,所以我写了一个简单的追加功能append function正常工作,但是当我使用for循环时,带有undefined value的额外节点将存储到head node中。代码在下面:

int main()
    {

            linked_list *list ;

            append_node(&list,4);
            append_node(&list,20);
            append_node(&list,200);

            print_linked_list(list);    // 4 20 200
                                        //prints just fine


    }

上面的代码工作正常,但是当我在下面这样做时:

int main()
{
       linked_list *list ;

       for(int i = 0;i < 5;i++)
            append_node(&list,i);

       print_linked_list(list);        // 11342689 0 1 2 3 4
                                       // prints a extra undefined node here at the head 
}

预期结果:0 1 2 3 4实际结果:11342689 0 1 2 3 4

这里是附加节点功能

void append_node(linked_list **head_ref,int value)
{
    linked_list *current = *head_ref;

    linked_list *new_node = (linked_list *)malloc(sizeof(linked_list));
    new_node->node_value = value;
    new_node->next_node = NULL;

    if(*head_ref == NULL)
    {
        *head_ref = new_node;
        return;
    }

    while(current->next_node)
        current = current->next_node;


    current->next_node = new_node;

    return ;
}

每当我使用loop时,列表都会得到具有不确定值的新头。列表的其余部分似乎正确。我不知道为什么会这样。有人可以告诉我吗?在此先感谢:)

c singly-linked-list
2个回答
2
投票

您应该将linked_list *list初始化为NULL,它应该可以正常工作。


0
投票

具有自动存储期限的变量不会隐式初始化。此声明中的Si

linked_list *list ;

已声明指针list具有不确定的值。

因此,程序具有未定义的行为。

您像那样天真地初始化了指针

linked_list *list = NULL;

此外,考虑到指针append_node是通过引用传递给函数的,因此可以更简单,更安全地定义函数list

您在这里。

int append_node( linked_list **head_ref, int value )
{
    linked_list *new_node = malloc( sizeof( linked_list ) );
    int success = new_node != NULL;

    if ( success )
    {
        new_node->node_value = value;
        new_node->next_node  = NULL;

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

        *head_ref = new_node;
    }

    return success;
}
© www.soinside.com 2019 - 2024. All rights reserved.