VOOZH about

URL: https://www.geeksforgeeks.org/dsa/delete-multiple-occurrences-of-key-in-linked-list-using-double-pointer/

⇱ Delete multiple occurrences of key in Linked list using double pointer - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Delete multiple occurrences of key in Linked list using double pointer

Last Updated : 11 Jul, 2025

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. Explanation: 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. 

Implementation:


Output
Created Linked List: 
 2 3 4 2 2 

Linked List after Deletion of 2: 
 3 4 

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space:O(1), as no extra space is required
Comment
Article Tags: