C: How To Free Nodes In The Linked List?


Answer :

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:

  1. check if head is NULL, if yes the list is empty and we just return

  2. Save the head in a tmp variable, and make head point to the next node on your list (this is done in head = head->next

  3. Now we can safely free(tmp) variable, and head just points to the rest of the list, go back to step 1

Simply by iterating over the list:

struct node *n = head; while(n){    struct node *n1 = n;    n = n->next;    free(n1); } 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?