Given a singly linked list, delete all occurrences of a given key in it. For example, consider the following list.
Input: 2 -> 2 -> 4 -> 3 -> 2 Key to delete = 2 Output: 4 -> 3
This is mainly an alternative of this post which deletes multiple occurrences of a given key using separate condition loops for head and remaining nodes. Here we use a double pointer approach to use a single loop irrespective of the position of the element (head, tail or between). The original method to delete a node from a linked list without an extra check for the head was explained by Linus Torvalds in his “25th Anniversary of Linux” TED talk. This article uses that logic to delete multiple recurrences of the key without an extra check for the head.
1. Store address of head in a double pointer till we find a non “key” node. This takes care of the 1st while loop to handle the special case of the head.
2. If a node is not “key” node then store the address of node->next in pp.
3. if we find a “key” node later on then change pp (ultimately node->next) to point to current node->next.
Following is C++ implementation for the same.
Created Linked List: 2 3 4 2 2 Linked List after Deletion of 2: 3 4
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Double Pointer (Pointer to Pointer) in C
- Delete all occurrences of a given key in a doubly linked list
- Delete all occurrences of a given key in a linked list
- Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
- Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
- Delete a Node from linked list without head pointer
- Pointer to an Array | Array Pointer
- What is a Pointer to a Null pointer
- Clone a linked list with next and random pointer | Set 1
- How to write C functions that modify head pointer of a Linked List?
- Clone a linked list with next and random pointer | Set 2
- Point to next higher value node in a linked list with an arbitrary pointer
- Clone a linked list with next and random pointer in O(1) space
- Point arbit pointer to greatest value right side node in a linked list
- Correct the Random Pointer in Doubly Linked List
- Insertion in a sorted circular linked list when a random pointer is given
- Delete a linked list using recursion
- Move all occurrences of an element to end in a linked list
- Remove all occurrences of duplicates from a sorted Linked List
- Double elements and append zeros in linked list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.