Previous:
- Linked lists in C [Singly linked list]
- Linked list traversal using while loop and recursion
- Concatenating two linked lists in C
- Inserting a new node in a linked list in C
Make sure that you are familiar with the concepts explained in the article[s] mentioned above before proceeding further.
We will proceed further by taking the linked list we made in the previous article.
We delete any node of a linked list by connecting thepredecessor node of the node to be deleted by the successor node of thesame node. For example, if we have a linked list a b c, then to delete the node b, we will connect a to c i.e., a c. But this will make the node binaccessible and this type of inaccessible nodes are called garbage and we need to clean this garbage. We do this cleaning by the use of free function. If you are not familiar with the free function then you can visit the Dynamic memory chapter of the C course. So, the steps to be followed for deletion of the node B from the linked list A B C are as follows:
- Create a temporary pointer to the node B.
- Connect node A to B.
- Free the node B.
The code representing the above steps is:
Here, before_node is thepredecessor of the node to be deleted.
temp = before_del->next We are making a temporary pointer to the node to be deleted.
before_del->next = temp->next Connecting thepredecessor of the node to be deleted with thesuccessor of the node to be deleted.
free[temp] Making the temp free.
And the overall code is:
Next:
- Array vs Linked list in C