【发布时间】:2017-10-07 06:21:50
【问题描述】:
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 吗?我在这里不太确定,所以headref-> head- >node(NULL),当前指向node(NULL),然后尝试在headref之后push num?
【问题讨论】:
-
由于添加了
Push,你可以看到两个函数的第一个参数struct node** headRef相同,所以你只需传递headRef。在第二种情况下,current->next是一个指针,所以&(current->next)是所需的指针。 -
@weathervane *headref 指的是指向节点的指针,对吗?当我使用 &(current->next) 和 headref 调用 push 时有什么不同?为什么 headref 是一个地址? headref 是指向那个指向节点的指针吗?如果我只用headref作为参数调用push,它只是复制指针吗?
标签: c pointers data-structures linked-list push