链表使用推送功能添加节点
linked list add node using push function
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(headRef, num);
,在这里为什么不使用符号作为 headref?如果参数只是 headref,它是否只是将指针复制到 push 函数?
headref 是指向节点指针的指针,如果我用参数 headref 调用 push,它是否只将 headref 复制到函数而不修改原始 headref?,我在这里不太确定,所以 headref-> head->node (NULL), current point to node(NULL), 然后尝试在 headref 之后推送 num?
headref is a pointer to a pointer to a node, if i call push with
argument headref, is it only copy headref to the function and not
modify the origin headref?
需要记住的一个方便的事情是:如果你想改变一个对象,你必须传入那个对象的地址。
虽然您没有显示整个程序,但(我认为)假设您在调用 AppendNode
时传入指向 headRef
的指针地址是安全的。您将这个地址传递给 Push
,以便 Push
可以取消引用一次并跳转到指向 headRef
的实际指针并在那里写一些东西。
如果您将 AppendNode
声明为 AppendNode(struct node* headRef, int num)
,那么您会将 &headRef
传递给 Push
。
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(headRef, num);
,在这里为什么不使用符号作为 headref?如果参数只是 headref,它是否只是将指针复制到 push 函数?
headref 是指向节点指针的指针,如果我用参数 headref 调用 push,它是否只将 headref 复制到函数而不修改原始 headref?,我在这里不太确定,所以 headref-> head->node (NULL), current point to node(NULL), 然后尝试在 headref 之后推送 num?
headref is a pointer to a pointer to a node, if i call push with argument headref, is it only copy headref to the function and not modify the origin headref?
需要记住的一个方便的事情是:如果你想改变一个对象,你必须传入那个对象的地址。
虽然您没有显示整个程序,但(我认为)假设您在调用 AppendNode
时传入指向 headRef
的指针地址是安全的。您将这个地址传递给 Push
,以便 Push
可以取消引用一次并跳转到指向 headRef
的实际指针并在那里写一些东西。
如果您将 AppendNode
声明为 AppendNode(struct node* headRef, int num)
,那么您会将 &headRef
传递给 Push
。