![](/img/trans.png)
[英]How can I insert a node in a singly linked list using recursion given: 1. a pointer to the head node 2. the index to insert the new node
[英]I am trying to insert a new starting/head node in a linked list...The commented out function doesn't work while the one below it does the job
// void insert_start(struct node *head, int data)
// {
// struct node *ptr = (struct node *)malloc(sizeof(struct node));
// ptr->next_ptr = head;
// ptr->data = data;
// head=ptr;
// }
上面的 function 不起作用,而下面的起作用
struct node *insert_start(struct node *head, int data)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->next_ptr = head;
ptr->data = data;
return ptr;
}
看到你的问题如下,在注释代码中,当你将名为head
的指针传递给你的 function 时,将创建另一个指向相同地址的指针,但你不能改变你的 main 中的原始指针指向什么,它是如下图所示:
如果要更改主 function 中的指针指向的内容,则必须将指针传递给该指针以更改其指向的内容,如下图所示:
为此,您可以修改评论的 function 如下:
void insert_start(struct node **head, int data)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->next_ptr = *head;
ptr->data = data;
*head = ptr;
}
当您调用 function 时,在您的主要 function 中,将指针的地址传递给它以更改它指向的内容: insert_start(&head, data);
这两个函数都声明为
void insert_start(struct node *head, int data);
处理指向用作参数表达式的头节点的指针的值的副本。
因此,在函数中更改副本不会影响原始指针的值。 它保持不变。
函数之间的唯一区别是第二个 function 将原始指针副本的修改后的值返回给调用者指向头节点。 因此,将 function 的返回值分配给指向头节点的原始指针,您可以更新其值。
关于您的第一个(评论)示例...
如评论中所述,C 按值传递 arguments。
在 C 中,如果要更改变量的值,则必须传递该变量的地址,而不是变量本身。
所以在你原来的 function 中:
void insert_start(struct node *head, int data)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->next_ptr = head;
ptr->data = data;
head=ptr;
}
*head
包含struct node
实例的地址值。 因此,返回时head
不会改变。
如果您想使用void
function 的形式来修改参数以允许它更改包含在*head
中的地址,那么您必须传递它的地址: **head
。 然后在 function 的主体中,进行如下修改。 (注意原因演员已被删除。)
void insert_start(struct node **head, int data)
{
struct node *ptr = malloc(sizeof(*ptr));
if(ptr)//verify return of malloc before using
{
ptr->data = data;
ptr->next_ptr = (*head);
(*head) = ptr;//setting head to address of new node
}
}
调用示例:(在 function 中调用,例如main()
)
struct node *new;
insert_start(&new, 10);//passing address of *new
if(!new)
{
//handle error
}
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.