我有这个练习,要求我创建一个函数,它根据包含一个整数的结构在新节点中添加一个数字到链表的头部 . 这是结构:
struct Node
{
int data;
struct Node *next;
};
直到现在都没问题 . 所以我创建了一个带有2个参数的参数:要添加的整数和指向链表头部的指针,但它不起作用 . 这是我的代码:
void push(struct Node* head, int new_data)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = head;
head = new_node;
}
所以,我所做的是我将new_node指向head指向的同一节点,之后我将新节点作为链表的新头 . 这似乎很合乎逻辑,虽然它不起作用 . 另一方面,当我给函数指定头指针的地址而不是指针本身时,它确实有效:
void push(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
/* 2. put in the data */
new_node->data = new_data;
/* 3. Make next of new node as head */
new_node->next = (*head_ref);
/* 4. move the head to point to the new node */
(*head_ref) = new_node;
}
这是双**的函数的主要内容:
int main()
{
struct Node* head = NULL;
push(&head,7);
push(&head,6);
push(&head,3);
return 0;
}
我知道第二个功能应该有效,但我不明白为什么有必要使用头部的地址而不是头部本身 . 如果有人能向我解释原因,我会很高兴,谢谢 .
1 回答
在简单的c代码中,你不能有引用(与c相反),而只是指针 .
存储在
head
指针变量中的值应该从对push()
的调用中更改,因此您需要传递head
变量的地址来更改(单个*指针)值 .当您使用c代码标记问题c++时,这是不必要的 .
您也可以通过引用获取指针参数: