In my previous article I showed how to create a linked list. Now if you no longer need the linked list in your program, you have to delete that. Otherwise, it will lead to memory leak. Here we’ll see how to delete linked list completely.
C Function to Delete Linked List
void delete_list(struct node **head) {
struct node *tmp;
while(*head) {
tmp = *head;
*head = (*head)->next;
free(tmp);
}
}
This function takes the head as input and traverse through the list. And in every iteration it deletes (frees memory) the node where head is pointing to and moves the head to next node. It continues until head becomes NULL, i.e., no node is left to be freed.