下面是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/