Program to Delete a Linked list

  • Write a C program to delete a singly linked list.
  • Write function in C to delete all nodes of a linked list.

To delete a linked list we need a pointer to the head node of linked list. We will write a function "deleteLinkedList" which takes head node of a linked list as input and deletes all nodes of given linked list one by one from head till tail node.

Singly linked list's node structure is as follows:
struct node {
    int data;
    struct node *next;
}

Algorithm to delete all nodes of a linked list
Let "head" be the pointer to pointer of head nodes of linked list to be deleted.
  • Using a while loop, we will traverse given linked list until (*head != NULL).
  • We will store the head pointer in a temporary pointer variable "temp".
  • Move head pointer to next node(*head = (*head)->next;).
  • Now, delete node pointed bu temp variable(free(temp)).
void deleteLinkedList(struct node **head) {
    struct node *temp;
    while (*head != NULL) {
        temp = *head;
        *head = (*head)->next;
        free(temp);
    }
}

C program to delete all nodes of a linked list

#include <stdio.h>
#include <stdlib.h>
 
/* A structure of linked list node */
struct node {
  int data;
  struct node *next;
} *head;

void initialize(){
    head = NULL;
}

/* 
Given a Inserts a node in front of a singly linked list. 
*/
void insert(int num) {
    /* Create a new Linked List node */
    struct node* newNode = (struct node*) malloc(sizeof(struct node));
    newNode->data  = num;
    /* Next pointer of new node will point to head node of linked list  */
    newNode->next = head;
    /* make new node as new head of linked list */
    head = newNode;
    printf("Inserted Element : %d\n", num);
}

void deleteLinkedList(struct node **head) {
    struct node *temp;
    while (*head != NULL) {
        temp = *head;
        *head = (*head)->next;
        free(temp);
    }
}

/*
Prints a linked list from head node till tail node 
*/
void printLinkedList(struct node *nodePtr) {
    if(nodePtr == NULL)
        printf("\nEmpty Linked List\n");
    while (nodePtr != NULL) {
        printf("%d", nodePtr->data);
        nodePtr = nodePtr->next;
        if(nodePtr != NULL)
            printf("-->");
    }
}
 
int main() {
    initialize();
    /* Creating a linked List*/
    insert(1);  
    insert(2); 
    insert(3); 
    insert(4);
    insert(5);
    
    printf("\nLinked List\n");
    printLinkedList(head);
    deleteLinkedList(&head);
    printLinkedList(head);
    
    return 0;
}
Output
Inserted Element : 8
Inserted Element : 3
Inserted Element : 2
Inserted Element : 7
Inserted Element : 9

Linked List
5-->4-->3-->2-->1
Empty Linked List