I came across this site, where removing last node of a linked list is implemented with the following code:
int remove_last(node_t * head) {
int retval = 0;
/* if there is only one item in the list, remove it */
if (head->next == NULL) {
head->val
free(head);
head = NULL;
return retval;
}
node_t * current = head;
while (current->next->next != NULL) {
current = current->next;
}
}
My question is simple, isn't this example wrong? I mean it will free the memory of the node only if there is only one node. In any other case it does not really do something, only keeps going to the next node in while (current->next->next != NULL)
loop. Am I not noticing something?
return
statement either...head->val
,head = NULL;
: no effect.