Skip to content
Related Articles
Remove all occurrences of key Y after the first occurrence node X in Linked List
• Last Updated : 03 Jun, 2021

Given a Linked List and two integers X and Y, the task is to remove all occurrences of Y after the first occurrence of a node with value X and print the modified linked list.

Examples:

Input: 7 → 20 → 9 → 10 → 20 → 14 → 15 → 20, X = 10, Y = 20
Output: 7 → 20 → 9 → 10 → 14 → 15

Input: LL: 10 → 20, X = 10, Y = 20
Output: LL: 10

Approach: The given problem can be solved by traversing the given Linked List and deleting all the nodes with value Y occurring after the node with value X. Follow the steps below to solve the problem:

• Initialize two list nodes, K and prev, to store the current head of the given Linked List and the previous node of the current head of the Linked List.
• Traverse the given Linked List until K becomes NULL and performs the following steps:
• Iterate the node K until a node with value X is found and simultaneously update the node prev as the previous node K.
• Store the node K in another variable, say temp, and traverse the Linked List until the node with value Y has occurred and simultaneously update the node prev to the previous node K.
• If the value of temp is NULL, then break out of the loop. Otherwise, update the next pointer of prev to the next pointer of temp and update temp to the next pointer of the node prev.
• After completing the above steps, print the modified Linked List.

Below is the implementation of the above approach:

## Java

 `// Java program for the above approach` `import` `java.io.*;``import` `java.util.*;``import` `java.util.LinkedList;` `class` `Main {` `    ``// Head of the linked list``    ``static` `Node head;` `    ``// Structure of a node``    ``// of a Linked List``    ``class` `Node {``        ``int` `data;``        ``Node next;` `        ``Node(``int` `d)``        ``{``            ``data = d;``            ``next = ``null``;``        ``}``    ``}` `    ``// Function to delete all occurrences``    ``// of key after first occurrence of A``    ``void` `deleteKey(``int` `A, ``int` `key)``    ``{``        ``// Stores the head node``        ``Node k = head, prev = ``null``;` `        ``while` `(k != ``null``) {` `            ``// Iterate until the``            ``// node A occurrs``            ``while` `(k != ``null``                   ``&& k.data != A) {` `                ``prev = k;``                ``k = k.next;``            ``}` `            ``Node temp = k;` `            ``while` `(temp != ``null``                   ``&& temp.data != key) {``                ``prev = temp;``                ``temp = temp.next;``            ``}` `            ``// If the entire linked``            ``// list has been traversed``            ``if` `(temp == ``null``)``                ``return``;` `            ``// Update prev and temp node``            ``prev.next = temp.next;``            ``temp = prev.next;``        ``}``    ``}` `    ``// Function to insert a new Node``    ``// at the front of the Linked List``    ``public` `void` `push(``int` `new_data)``    ``{``        ``// Create a new node``        ``Node new_node = ``new` `Node(new_data);` `        ``// Insert the node at the front``        ``new_node.next = head;` `        ``// Update the head of LL``        ``head = new_node;``    ``}` `    ``// Function to print the Linked List``    ``public` `void` `printList()``    ``{``        ``// Stores the head node``        ``Node tnode = head;` `        ``// Traverse the Linked List``        ``while` `(tnode != ``null``) {` `            ``// Print the node``            ``System.out.print(tnode.data + ``" "``);` `            ``// Update tnode``            ``tnode = tnode.next;``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``Main list = ``new` `Main();``        ``list.push(``20``);``        ``list.push(``15``);``        ``list.push(``10``);``        ``list.push(``20``);``        ``list.push(``10``);``        ``list.push(``9``);``        ``list.push(``20``);``        ``list.push(``7``);``        ``int` `X = ``10``;``        ``int` `Y = ``20``;` `        ``list.deleteKey(X, Y);` `        ``// Print the updated list``        ``list.printList();``    ``}``}`

## Python3

 `# Python3 program for the above approach` `# Structure of a node``# of a Linked List``class` `Node:``    ` `    ``def` `__init__(``self``, x):``        ` `        ``self``.data ``=` `x``        ``self``.left ``=` `None``        ``self``.right ``=` `None` `# Function to delete all occurrences``# of key after first occurrence of A``def` `deleteKey(head, A, key):``    ` `    ``# Stores the head node``    ``k, prev ``=` `head, ``None` `    ``while` `(k !``=` `None``):` `        ``# Iterate until the``        ``# node A occurrs``        ``while` `(k !``=` `None` `and` `k.data !``=` `A):``            ``prev ``=` `k``            ``k ``=` `k.``next` `        ``temp ``=` `k` `        ``while` `(temp !``=` `None` `and` `temp.data !``=` `key):``            ``prev ``=` `temp``            ``temp ``=` `temp.``next` `        ``# If the entire linked``        ``# list has been traversed``        ``if` `(temp ``=``=` `None``):``            ``return` `        ``# Update prev and temp node``        ``prev.``next` `=` `temp.``next``        ``temp ``=` `prev.``next` `        ``return` `head` `# Function to insert a new Node``# at the front of the Linked List``def` `push(head, new_data):``    ` `    ``# Create a new node``    ``new_node ``=` `Node(new_data)` `    ``# Insert the node at the front``    ``new_node.``next` `=` `head` `    ``# Update the head of LL``    ``head ``=` `new_node``    ``return` `head` `# Function to print the Linked List``def` `printList(head):``    ` `    ``# Stores the head node``    ``tnode ``=` `head` `    ``# Traverse the Linked List``    ``while` `(tnode.``next` `!``=` `None``):` `        ``# Print the node``        ``print``(tnode.data, end ``=` `" "``)` `        ``# Update tnode``        ``tnode ``=` `tnode.``next` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``list` `=` `None``    ``list` `=` `push(``list``, ``20``)``    ``list` `=` `push(``list``, ``15``)``    ``list` `=` `push(``list``, ``10``)``    ``list` `=` `push(``list``, ``20``)``    ``list` `=` `push(``list``, ``10``)``    ``list` `=` `push(``list``, ``9``)``    ``list` `=` `push(``list``, ``20``)``    ``list` `=` `push(``list``, ``7``)``    ``X ``=` `10``    ``Y ``=` `20` `    ``list` `=` `deleteKey(``list``, X, Y)` `    ``# Print the updated list``    ``printList(``list``)` `# This code is contributed by mohit kumar 29`

## Javascript

 ``
Output:
`7 20 9 10 10 15`

Time Complexity: O(N)
Auxiliary Space: O(1)

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live

My Personal Notes arrow_drop_up