![](/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.