Delete multiple occurrences of key in Linked list using double pointer Last Updated : 10 Jan, 2024 Comments Improve Suggest changes Like Article Like Report 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 = 2Output: 4 -> 3 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.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: C++ // CPP program to delete multiple // occurrences of a key using single // loop. #include <iostream> using namespace std; // A linked list node struct Node { int data; struct Node* next; }; struct Node* head = NULL; void printList(struct Node* node) { while (node != NULL) { printf(" %d ", node->data); node = node->next; } } void push(int new_data) { struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (head); (head) = new_node; } void deleteEntry(int key) { // Start from head struct Node** pp = &head; while (*pp) { struct Node* entry = *pp; // If key found, then put // next at the address of pp // delete entry. if (entry->data == key) { *pp = entry->next; delete (entry); } // Else move to next else pp = &(entry->next); } } int main() { push(2); push(2); push(4); push(3); push(2); int key = 2; // key to delete puts("Created Linked List: "); printList(head); printf("\n"); deleteEntry(key); printf("\nLinked List after Deletion of 2: \n"); printList(head); return 0; } Java class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } public class DeleteMultipleOccurrences { static Node head = null; static void printList(Node node) { while (node != null) { System.out.print(" " + node.data + " "); node = node.next; } } static void push(int newData) { Node newNode = new Node(newData); newNode.next = head; head = newNode; } static void deleteEntry(int key) { Node pp = head; Node prev = null; while (pp != null) { Node entry = pp; // If key found, then adjust next pointers // and continue if (entry.data == key) { if (prev != null) { prev.next = entry.next; } else { head = entry.next; } } else { prev = entry; } // Move to the next node pp = entry.next; } } public static void main(String[] args) { push(2); push(2); push(4); push(3); push(2); int key = 2; // key to delete System.out.println("Created Linked List:"); printList(head); System.out.println("\nLinked List after Deletion of 2:"); deleteEntry(key); printList(head); } } Python3 # Python3 program to delete multiple # occurrences of a key using single # loop. class Node: def __init__(self, data): self.data = data self.next = None # Function to print the linked list def printList(node): while node: print(node.data, end=" ") node = node.next print() # Function to insert a new node at the beginning def push(new_data): new_node = Node(new_data) new_node.next = head globals()['head'] = new_node # Function to delete all occurrences of a key def delete_entry(key): global head # Start from head entry = head prev = None # Traverse the linked list while entry: # If key found, update the next of the previous node if entry.data == key: if prev: prev.next = entry.next else: head = entry.next # Delete the current entry del entry # Move to the next node entry = prev.next if prev else head else: # Move to the next node prev = entry entry = entry.next # Driver code if __name__ == '__main__': head = None push(2) push(2) push(4) push(3) push(2) key = 2 # key to delete print("Created Linked List:") printList(head) print("\nLinked List after Deletion of 2:") delete_entry(key) printList(head) # This code is contributed by shivamgupta0987654321 C# // C# program to delete multiple // occurrences of a key using single // loop. using System; // A linked list node public class Node { public int data; public Node next; } public class LinkedList { static Node head = null; static void PrintList(Node node) { while (node != null) { Console.Write(" " + node.data + " "); node = node.next; } } static void Push(int newData) { Node newNode = new Node(); newNode.data = newData; newNode.next = head; head = newNode; } static void DeleteEntry(int key) { // Start from head Node pp = head; Node prev = null; while (pp != null) { // If key found, then skip the node if (pp.data == key) { if (prev != null) { prev.next = pp.next; } else { head = pp.next; } pp = pp.next; } // Else move to next else { prev = pp; pp = pp.next; } } } public static void Main(string[] args) { Push(2); Push(2); Push(4); Push(3); Push(2); int key = 2; // key to delete Console.WriteLine("Created Linked List: "); PrintList(head); Console.WriteLine(); DeleteEntry(key); Console.WriteLine("Linked List after Deletion of 2: "); PrintList(head); } } JavaScript // A linked list node class Node { constructor(data) { this.data = data; this.next = null; } } let head = null; // Function to print the linked list function printList(node) { while (node !== null) { console.log(` ${node.data} `); node = node.next; } } // Function to insert a new node at the beginning of the linked list function push(new_data) { const new_node = new Node(new_data); new_node.next = head; head = new_node; } // Function to delete all occurrences of a key in the linked list function deleteEntry(key) { let current = head; let prev = null; while (current !== null) { if (current.data === key) { if (prev === null) { head = current.next; } else { prev.next = current.next; } current = current.next; } else { prev = current; current = current.next; } } } // Insert some values into the linked list push(2); push(2); push(4); push(3); push(2); // Print the original linked list console.log("Created Linked List: "); printList(head); console.log("\n"); // Delete all occurrences of key = 2 const keyToDelete = 2; deleteEntry(keyToDelete); // Print the linked list after deletion console.log(`Linked List after Deletion of ${keyToDelete}: `); printList(head); OutputCreated 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 More infoAdvertise with us Next Article Delete multiple occurrences of key in Linked list using double pointer N NayanGadre Follow Improve Article Tags : Linked List C/C++ Puzzles Data Structures DSA cpp-pointer cpp-double-pointer +2 More Practice Tags : Data StructuresLinked List Similar Reads Delete all occurrences of a given key in a doubly linked list Given a doubly linked list and a key x. The problem is to delete all occurrences of the given key x from the doubly linked list. Examples: Algorithm: delAllOccurOfGivenKey(head_ref, x) if head_ref == NULL return Initialize current = head_ref Declare next while current != NULL if current->data == 14 min read Delete all occurrences of a given key in a linked list Given a singly linked list, the task is to delete all occurrences of a given key in it.Examples:Input: head: 2 -> 2 -> 1 -> 8 -> 2 -> NULL, key = 2Output: 1 -> 8 -> NULL Explanation: All occurrences of the given key = 2, is deleted from the Linked ListInput: head: 1 -> 1 - 8 min read Remove all occurrences of one Linked list in another Linked list Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 - 9 min read Delete first occurrence of given Key from a Linked List Given a linked list and a key to be deleted. The task is to delete the first occurrence of the given key from the linked list. Note: The list may have duplicates. Examples: Input: list = 1->2->3->5->2->10, key = 2Output: 1->3->5->2->10Explanation: There are two instances o 10 min read Move all occurrences of an element to end in a linked list Given a linked list and a key in it, the task is to move all occurrences of the given key to the end of the linked list, keeping the order of all other elements the same. Examples: Input : 1 -> 2 -> 2 -> 4 -> 3 key = 2 Output : 1 -> 4 -> 3 -> 2 -> 2 Input : 6 -> 6 -> 7 15+ min read Delete a Node in a Singly Linked List with Only a Pointer Given only a pointer to a node to be deleted in a singly linked list. The task is to delete that node from the list. Note: The given pointer does not point to the last node of the linked list.Examples:Input: LinkedList: 1->2->3->4->5, delete_ptr = 2Output: LinkedList: 1->3->4->5 6 min read Delete a Doubly Linked List node at a given position Given a doubly linked list and a position pos, the task is to delete the node at the given position from the beginning of Doubly Linked List.Input: LinkedList: 1<->2<->3, pos = 2Output: LinkedList: 1<->3Input: LinkedList: 1<->2<->3, pos = 1Output: LinkedList: 2<-> 9 min read Delete a linked list using recursion Given a linked list, the task is to delete the linked list using recursion.Examples: Input: Linked List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: NULLExplanation: Linked List is DeletedInput: Linked List = 1 -> 12 -> 1 -> 4 -> 1 -> NULL Output: NULLExplanation: Linked Lis 5 min read Remove all occurrences of duplicates from a sorted Linked List Given a sorted linked list, delete all nodes that have duplicate numbers (all occurrences), leaving only numbers that appear once in the original list. Examples: Input : 23->28->28->35->49->49->53->53 Output : 23->35 Input : 11->11->11->11->75->75 Output : empt 10 min read Modify a Linked List to contain last occurrences of every duplicate element Given an unsorted Singly Linked List consisting of N nodes that may contain duplicate elements, the task is to remove all but the last occurrence of duplicate elements from the Linked List. Examples: Input: 1 -> 2 -> 7 -> 3 -> 2 -> 5 -> 1Output: 7 -> 3 -> 2 -> 5 -> 1Exp 10 min read Like