在c中向链表插入节点
请解释一下在c中向链表插入节点,c,linked-list,C,Linked List,请解释一下 new_node->next = (*head_ref); (*head_ref) = new_node; 这是下面的代码 /* Utility function to insert a node at the beginning */ void push(struct node **head_ref, int new_data) { struct node *new_node = (struct node *) malloc(sizeof(struct node))
new_node->next = (*head_ref);
(*head_ref) = new_node;
这是下面的代码
/* Utility function to insert a node at the beginning */
void push(struct node **head_ref, int new_data)
{
struct node *new_node = (struct node *) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
这正是评论所说的。
在开始处插入新节点,并更新head_ref以指向新的开始处。这就是在C中如何将简单节点添加到链表的开始处。代码仅保留对头部的引用,当添加新节点时,它将添加到开始处,新插入的节点将被视为新的头部 在代码中,第一行在开头添加新节点。这是通过将当前列表(由标题指向)附加到下一个新节点来实现的 第二行将新节点标记为列表头 请在下面的链接中查看对上述逻辑的全面图片解释
头指针在每次“推送”时都会被修改,因此它需要通过地址传递(从而取消对get和set值的引用)。一种常见的替代方法是简单地使用函数返回值作为新的头指针。()。阅读按值传递参数与按引用传递参数之间的区别。可能重复:按引用传递参数的优点是什么?