C: How to free nodes in the linked list?
Simply by iterating over the list:
struct node *n = head;
while(n){
struct node *n1 = n;
n = n->next;
free(n1);
}
An iterative function to free your list:
void freeList(struct node* head)
{
struct node* tmp;
while (head != NULL)
{
tmp = head;
head = head->next;
free(tmp);
}
}
What the function is doing is the follow:
check if
head
is NULL, if yes the list is empty and we just returnSave the
head
in atmp
variable, and makehead
point to the next node on your list (this is done inhead = head->next
- Now we can safely
free(tmp)
variable, andhead
just points to the rest of the list, go back to step 1