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
headis NULL, if yes the list is empty and we just return -
Save the
headin atmpvariable, and makeheadpoint to the next node on your list (this is done inhead = head->next - Now we can safely
free(tmp)variable, andheadjust points to the rest of the list, go back to step 1