Saturday, September 6, 2025
HomeData Modelling & AIC Program For Writing A Function To Delete A Linked List

C Program For Writing A Function To Delete A Linked List

Algorithm For C:
Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted.

Implementation:

C




// C program to delete a linked list
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
 
// Link list node
struct Node
{
    int data;
    struct Node* next;
};
 
// Function to delete the entire
// linked list
void deleteList(struct Node** head_ref)
{
   // define head_ref to get the real head
   struct Node* current = *head_ref;
   struct Node* next;
 
   while (current != NULL)
   {
       next = current->next;
       free(current);
       current = next;
   }
   
   // Define head_ref to affect the real
   // head back in the caller.
   *head_ref = NULL;
}
 
/* Given a reference (pointer to pointer) to
   the head of a list and an int, push a new
   node on the front of the list. */
void push(struct Node** head_ref,
          int new_data)
{
    // Allocate node
    struct Node* new_node =
           (struct Node*) malloc(sizeof(struct Node));
 
    // Put in the data 
    new_node->data  = new_data;
    
    // Link the old list of the new node
    new_node->next = (*head_ref);
    
    // Move the head to point to the new node
    (*head_ref)    = new_node;
}
 
// Driver code
int main()
{
    // Start with the empty list
    struct Node* head = NULL;
    
    // Use push() to construct list
    // 1->12->1->4->1 
    push(&head, 1);
    push(&head, 4);
    push(&head, 1);
    push(&head, 12);
    push(&head, 1);  
    
    printf("Deleting linked list");
    deleteList(&head); 
    
    printf("Linked list deleted");
}


Output:

Deleting linked list
Linked list deleted

Time Complexity: O(n) 
Auxiliary Space: O(1)

Please refer complete article on Write a function to delete a Linked List for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS