struct node* AppendNode(struct node** headRef, int num) {
struct node* current = *headRef;
// special case for the empty list
if (current == NULL) {
Push(headRef, num); ->why not use & in front of headref?
} else {
// Locate the last node
while (current->next != NULL) {
current = current->next;
}
// Build the node after the last node
Push(&(current->next), num);
}
}
void Push(struct node** headRef, int data) {
struct node* newNode = malloc(sizeof(struct node));
newNode->data = data;
newNode->next = *headRef; // The '*' to dereferences back to the real head
*headRef = newNode; // ditto
}
这是使用push添加节点的代码,但是我在这一部分感到困惑,Push(headRef,num);
,在这里为什么不使用&符作为headref?如果参数仅是headref,是否仅将指针复制到push函数?
headref是指向节点的指针的指针,如果我用参数headref调用push,是否仅将headref复制到函数而不修改原始的headref ?? NULL),当前指向node(NULL),然后尝试在headref之后推送num?
最佳答案
headref是一个指向节点的指针,如果我用
参数headref,是否仅将headref复制到函数,而不复制
修改原始headref?
一个容易记住的事情是:如果要更改对象,则必须传递该对象的地址。
尽管您没有显示整个程序,但是(我认为)可以安全地假设您在调用headRef
时将指针的地址传递给AppendNode
。并且是您将此地址传递给Push
的地址,以便Push
可以取消引用一次,然后跳转到指向headRef
的实际指针,然后在其中写入内容。
如果您将AppendNode
声明为AppendNode(struct node* headRef, int num)
,那么您应该将&headRef
传递给Push
。