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 return -
Save 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