gpt4 book ai didi

c - 为什么以下在单链表末尾插入节点的代码不起作用?

转载 作者:行者123 更新时间:2023-11-30 20:35:47 26 4
gpt4 key购买 nike

下面是C语言代码:

函数调用:

insert(&head,value);

void insert(struct node** headref,int value)
{
struct node* head = (*headref);

while( head!=NULL )
{

head= head->link;
}

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

new_node->data=value;
new_node->link=NULL;

head=new_node;
}

最佳答案

您需要将列表的最后一个元素链接到 new_node 否则您将失去列表的链接性(如果有这样的单词:))。您需要在循环中存储已有的 2 个指针 - head 和一个指向前一个元素(head 之前的元素)的指针。请特别注意列表为空的情况!

关于c - 为什么以下在单链表末尾插入节点的代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38052187/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com