Background is that I am experimenting with pointer-to-pointer in C by implementing a linked list. My question is regarding the difference in the two pieces of code and why the first one is giving expected output, but not the other one. Why does the first piece of code not advance head "outsite" the function which code 2 seems to do?
void add_node(int x, Node **head){
if(*head == NULL){
Node *new_node = (Node*) malloc(sizeof(new_node));
new_node->x = x;
*head = new_node;
} else {
Node *n = *head;
while(n->next != NULL){
n = n->next;
}
Node *new_node = (Node*) malloc(sizeof(new_node));
new_node->x = x;
n->next = new_node;
}
}
Output is as expected if I add 4 elements and after each addition print the list: 1 | 12 | 123 | 1234
void add_node(int x, Node **head){
if(*head == NULL){
Node *new_node = (Node*) malloc(sizeof(new_node));
new_node->x = x;
*head = new_node;
} else {
while((*head)->next != NULL){
*head = (*head)->next;
}
Node *new_node = (Node*) malloc(sizeof(new_node));
new_node->x = x;
(*head)->next = new_node;
}
}
Output is following: 1 | 12 | 23 | 34