0
votes
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
}

this is code to add node using push, but i was confuse in this part, Push(headRef, num);

,in here why not using ampersand for headref? if the argument is only headref, is it only copy the pointer to the push function?

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?, im not quite sure here, so headref-> head->node (NULL), current point to node(NULL),, then try to push num after headref?

1
Since adding Push, you can see that both functions have the same first parameter struct node** headRef so you just pass headRef. In the second case current->next is a pointer, so &(current->next) is the pointer-to-pointer required. - Weather Vane
@weathervane *headref refer to the pointer to node right? what is the different when i call push using &(current->next) and headref? and why headref is an address? headref is a pointer to pointer that point node right? and if i only call push with headref as argument, is it only copy the pointer? - fiksx

1 Answers

0
votes

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?

A handy thing to remember is this: if you want to change an object, you have to pass in the address of that object.

Although you have not shown the entire program, it would be safe (I think) to assume that you pass in the address of the pointer to headRef when calling AppendNode. And it is this address that you pass on to Push so that Push can de-reference this once and hop to the actual pointer to headRef and write something there.

Had you declared AppendNode as AppendNode(struct node* headRef, int num), then you would have passed &headRef to Push.