Write a program to delete a linked list. Given a linked list, we have to write a code to delete a linked list.
To delete a complete linked list, traverse all the nodes of a linked list and delete one by one.
Print Middle Element of a Linked List
How to Delete a Linked List
To delete a node one by one maintain two pointers. The first pointer points to head and the second pointer keeps the reference to next node. So when a node is free, you can assign the reference of next node using the second pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
void delete(){ /* Two pointers first and second. */ struct node* first = head; struct node* second; /* Iterate while list is not empty. */ while(first != NULL){ /* Keep pointer to next node. */ second = first->next; /* Free first */ free(first); /* Assign reference to first node. */ first = second; } /* Once all the node is deleted assign NULL */ head = NULL; } |
Reverse a linked list using iteration.
Reverse a linked list using Recursion.
C Program to Delete a Linked List
We have discussed the logic of a program, let’s implement it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
#include <stdio.h> /* create node. */ struct node{ int data; struct node* next; }; /* head is global. */ struct node* head; /* Function to insert new node. */ void insert(int data){ struct node* newNode; /* malloc is used to allocate memory. */ newNode = (struct node*)malloc(sizeof(struct node*)); newNode->data = data; newNode->next = head; head = newNode; } void delete(){ struct node* first = head; struct node* second; while(first!=NULL){ /* Keep pointer to next node. */ second = first->next; /* Free first */ free(first); first = second; } /* Once all the node is deleted assign NULL */ head = NULL; } void print(){ struct node* p; p = head; while(p != NULL){ printf("%d\n",p->data); p=p->next; } printf("\n"); } int main(void) { head = NULL; insert(3); insert(7); insert(8); printf("After insertion of linked list\n"); print(); delete(); printf("After deletion of complete linked list"); print(); return 0; } |
Output –
1 2 3 4 5 6 |
After insertion of linked list 8 7 3 After deleteion of complete linked list |
Time Complexity : O(n)
Space Complexity : O(1)