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

标签 c data-structures linked-list singly-linked-list

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

相关文章:

c - 在 Antlr4 中保留空格和换行符

python - 您将什么称为允许持久操作的非持久数据结构?

Java 一个语句中有两个等号?

c++ - 设计 L-System 数据结构 (C++)

arrays - 根据第二个数组的元素对数组进行排序

java - 对 LinkedList 中 ListIterator 的 add() 方法感到困惑

algorithm - 查找单链表的倒数第 k 个元素 : answer explanation

c - 使用 ASCII 值打印大字体字符,如二极管屏幕

C函数使用指针更改字符串

c - 了解多线程共享资源 : shmid, shmat、shmdt