C Program to Delete Linked List

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.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0