Delete all occurrences of a given key in a linked list

Given a singly linked list, delete all occurrences of a given key in it. For example, consider the following list.

Example:

Input: 2 -> 2 -> 1 -> 8 -> 2 ->  3 ->  2 -> 7
       Key to delete = 2
Output:  1 -> 8 -> 3 -> 7 

This is mainly an extension of this post which deletes first occurrence of a given key
We need to first check for all occurrences at head node and change the head node appropriately. Then we need to check for all occurrences inside a loop and delete them one by one. 

Below is the implementation of the above idea:

C

filter_none

edit
close

play_arrow

link
brightness_4
code

// C Program to delete all occurrences of a given key in
// linked list
#include <stdio.h>
#include <stdlib.h>
 
// A linked list node
struct Node
{
    int data;
    struct Node* next;
};
 
/* Given a reference (pointer to pointer) to the head of a
   list and an int, inserts a new node on the front of the
   list. */
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
 
/* Given a reference (pointer to pointer) to the head of a
   list and a key, deletes all occurrence of the given key
   in linked list */
void deleteKey(struct Node** head_ref, int key)
{
    // Store head node
    struct Node *temp = *head_ref, *prev;
 
    // If head node itself holds the key or multiple
    // occurrences of key
    while (temp != NULL && temp->data == key)
    {
        *head_ref = temp->next; // Changed head
        free(temp); // free old head
        temp = *head_ref; // Change Temp
    }
 
    // Delete occurrences other than head
    while (temp != NULL)
    {
        // Search for the key to be deleted, keep track of
        // the previous node as we need to change
        // 'prev->next'
        while (temp != NULL && temp->data != key)
        {
            prev = temp;
            temp = temp->next;
        }
 
        // If key was not present in linked list
        if (temp == NULL)
            return;
 
        // Unlink the node from linked list
        prev->next = temp->next;
 
        free(temp); // Free memory
 
        // Update Temp for next iteration of outer loop
        temp = prev->next;
    }
}
 
// This function prints contents of linked list starting
// from the given node
void printList(struct Node* node)
{
    while (node != NULL)
    {
        printf(" %d ", node->data);
        node = node->next;
    }
}
 
// Driver code
int main()
{
    // Start with the empty list
    struct Node* head = NULL;
 
    push(&head, 7);
    push(&head, 2);
    push(&head, 3);
    push(&head, 2);
    push(&head, 8);
    push(&head, 1);
    push(&head, 2);
    push(&head, 2);
 
    int key = 2; // key to delete
 
    puts("Created Linked List: ");
    printList(head);
 
    // Function call
    deleteKey(&head, key);
    puts("\nLinked List after Deletion is:");
 
    printList(head);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to delete all occurrences
// of a given key in linked list
class LinkedList
{
    static Node head; // head of list
 
    /* Linked list Node*/
    class Node
    {
        int data;
        Node next;
        Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    /* Given a key, deletes all occurrence
    of the given key in linked list */
    void deleteKey(int key)
    {
        // Store head node
        Node temp = head, prev = null;
 
        // If head node itself holds the key
        // or multiple occurrences of key
        while (temp != null && temp.data == key)
        {
            head = temp.next; // Changed head
            temp = head; // Change Temp
        }
 
        // Delete occurrences other than head
        while (temp != null)
        {
            // Search for the key to be deleted,
            // keep track of the previous node
            // as we need to change 'prev->next'
            while (temp != null && temp.data != key)
            {
                prev = temp;
                temp = temp.next;
            }
 
            // If key was not present in linked list
            if (temp == null)
                return;
 
            // Unlink the node from linked list
            prev.next = temp.next;
 
            // Update Temp for next iteration of outer loop
            temp = prev.next;
        }
    }
 
    /* Inserts a new Node at front of the list. */
    public void push(int new_data)
    {
        Node new_node = new Node(new_data);
        new_node.next = head;
        head = new_node;
    }
 
    /* This function prints contents of linked list
    starting from the given node */
    public void printList()
    {
        Node tnode = head;
        while (tnode != null)
        {
            System.out.print(tnode.data + " ");
            tnode = tnode.next;
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        LinkedList llist = new LinkedList();
 
        llist.push(7);
        llist.push(2);
        llist.push(3);
        llist.push(2);
        llist.push(8);
        llist.push(1);
        llist.push(2);
        llist.push(2);
 
        int key = 2; // key to delete
 
        System.out.println("Created Linked list is:");
        llist.printList();
 
        // Function call
        llist.deleteKey(key);
 
        System.out.println(
            "\nLinked List after Deletion is:");
        llist.printList();
    }
}
 
// This code is contributed by Shubham

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to delete all occurrences
# of a given key in linked list
 
# Link list node
 
 
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
# Given a reference (pointer to pointer)
# to the head of a list and an int,
# inserts a new node on the front of the list.
 
 
def push(head_ref, new_data):
    new_node = Node(0)
    new_node.data = new_data
    new_node.next = (head_ref)
    (head_ref) = new_node
    return head_ref
 
# Given a reference (pointer to pointer)
# to the head of a list and a key,
# deletes all occurrence of the given key
# in linked list
 
 
def deleteKey(head_ref, key):
 
    # Store head node
    temp = head_ref
    prev = None
 
    # If head node itself holds the key
    # or multiple occurrences of key
    while (temp != None and temp.data == key):
        head_ref = temp.next  # Changed head
        temp = head_ref         # Change Temp
 
    # Delete occurrences other than head
    while (temp != None):
 
        # Search for the key to be deleted,
        # keep track of the previous node
        # as we need to change 'prev.next'
        while (temp != None and temp.data != key):
            prev = temp
            temp = temp.next
 
        # If key was not present in linked list
        if (temp == None):
            return head_ref
 
        # Unlink the node from linked list
        prev.next = temp.next
 
        # Update Temp for next iteration of outer loop
        temp = prev.next
    return head_ref
 
# This function prints contents of linked list
# starting from the given node
 
 
def printList(node):
    while (node != None):
        print(node.data, end=" ")
        node = node.next
 
 
# Driver Code
if __name__ == '__main__':
 
    # Start with the empty list
    head = None
 
    head = push(head, 7)
    head = push(head, 2)
    head = push(head, 3)
    head = push(head, 2)
    head = push(head, 8)
    head = push(head, 1)
    head = push(head, 2)
    head = push(head, 2)
 
    key = 2  # key to delete
 
    print("Created Linked List: ")
    printList(head)
 
    # Function call
    head = deleteKey(head, key)
    print("\nLinked List after Deletion is: ")
 
    printList(head)
 
# This code is contributed by Arnab Kundu

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to delete all occurrences
// of a given key in linked list
using System;
 
class GFG
{
    static Node head; // head of list
 
    /* Linked list Node*/
    public class Node
    {
        public int data;
        public Node next;
        public Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    /* Given a key, deletes all occurrence
    of the given key in linked list */
    void deleteKey(int key)
    {
        // Store head node
        Node temp = head, prev = null;
 
        // If head node itself holds the key
        // or multiple occurrences of key
        while (temp != null && temp.data == key)
        {
            head = temp.next; // Changed head
            temp = head; // Change Temp
        }
 
        // Delete occurrences other than head
        while (temp != null)
        {
            // Search for the key to be deleted,
            // keep track of the previous node
            // as we need to change 'prev->next'
            while (temp != null && temp.data != key)
            {
                prev = temp;
                temp = temp.next;
            }
 
            // If key was not present in linked list
            if (temp == null)
                return;
 
            // Unlink the node from linked list
            prev.next = temp.next;
 
            // Update Temp for next iteration of outer loop
            temp = prev.next;
        }
    }
 
    /* Inserts a new Node at front of the list. */
    public void Push(int new_data)
    {
        Node new_node = new Node(new_data);
        new_node.next = head;
        head = new_node;
    }
 
    /* This function prints contents of linked list
    starting from the given node */
    public void printList()
    {
        Node tnode = head;
        while (tnode != null)
        {
            Console.Write(tnode.data + " ");
            tnode = tnode.next;
        }
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        GFG llist = new GFG();
 
        llist.Push(7);
        llist.Push(2);
        llist.Push(3);
        llist.Push(2);
        llist.Push(8);
        llist.Push(1);
        llist.Push(2);
        llist.Push(2);
 
        int key = 2; // key to delete
 
        Console.WriteLine("Created Linked list is:");
        llist.printList();
 
        // Function call
        llist.deleteKey(key);
 
        Console.WriteLine(
            "\nLinked List after Deletion is:");
        llist.printList();
    }
}
 
// This code is contributed by 29AjayKumar

chevron_right


Output

Created Linked List: 
 2  2  1  8  2  3  2  7 
Linked List after Deletion is:
 1  8  3  7 

This article is contributed by Saransh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

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.




My Personal Notes arrow_drop_up