I have this code which creates new node at the very front:
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
And I have this code which creates a new node after another one:
void insertAfter(struct Node* prev_node, int new_data)
{
if (prev_node == NULL)
{
printf("the given previous node cannot be NULL");
return;
}
struct Node* new_node =(struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
I understand that if we pass a single pointer a.k.a. head in the first case, the changes will take effect only in the push function, rather than the whole program. That's why we use reference to head to change what it points to.
In the second case, though, we pass a single pointer. I just don't understand why when we are not using reference to the previous node, the code will still work even though we are changing next to point to the new node.
Shouldn't these changes remain only in the insertAfter function?