The Wayback Machine - https://web.archive.org/web/20240927192642/https://www.geeksforgeeks.org/delete-occurrences-given-key-linked-list/
Open In App

Delete all occurrences of a given key in a linked list

Last Updated : 04 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 = 2
Output: 1 -> 8 -> NULL

Delete-all-occurrences-of-a-given-key-in-a-linked-list

Explanation: All occurrences of the given key = 2, is deleted from the Linked List


Input: head: 1 -> 1 -> 1 -> 4 -> 1 -> NULL, key = 1
Output: 4 -> NULL

Delete-all-occurrences-of-a-given-key-in-a-linked-list_1

Explanation: All occurrences of the given key = 1, is deleted from the Linked List.

Approach:

The Idea is to traverse the list while maintaining a prev pointer to track the previous node. If the current node contains the key, update the next pointer of the prev node to the current node, effectively removing it from the list. This process continues until the end of the list, ensuring all nodes with the specified key are removed.

Below is the implementation of the above idea:

C++
// Iterative C++ program to delete all occurrences of a 
// given key in a linked list
#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int new_data) {
        data = new_data;
        next = nullptr;
    }
};

// Given the head of a list, delete all occurrences of a 
// given key and return the new head of the list
Node* deleteOccurrences(Node* head, int key) {

    // Initialize pointers to traverse the linked list
    Node *curr = head, *prev = nullptr;

    // Traverse the list to delete all occurrences
    while (curr != nullptr) {

        // If current node's data is equal to key
        if (curr->data == key) {

            // If node to be deleted is head node
            if (prev == nullptr) {
                head = curr->next;
            } 
          
            else {
                prev->next = curr->next;
            }

            // Move to the next node
            curr = curr->next;

        } 
        
        else {
          
            // Move pointers one position ahead
            prev = curr;
            curr = curr->next;
        }
    }

    return head;
}

void printList(Node* curr) {
    while (curr != nullptr) {
        cout << " " << curr->data;
        curr = curr->next;
    }
}

int main() {

    // Create a hard-coded linked list:
    // 2 -> 2 -> 1 -> 8 -> 2 -> NULL
    Node* head = new Node(2);
    head->next = new Node(2);
    head->next->next = new Node(1);
    head->next->next->next = new Node(8);
    head->next->next->next->next = new Node(2);

    int key = 2;
    head = deleteOccurrences(head, key);
    printList(head);
    return 0;
}
C
// Iterative C program to delete all occurrences of a 
// given key in a linked list
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

// Given the head of a list, delete all occurrences of a 
// given key and return the new head of the list
struct Node* deleteOccurrences(struct Node* head, int key) {

    // Initialize pointers to traverse the linked list
    struct Node *curr = head, *prev = NULL;

    // Traverse the list to delete all occurrences
    while (curr != NULL) {

        // If current node's data is equal to key
        if (curr->data == key) {

            // If node to be deleted is head node
            if (prev == NULL) {
                head = curr->next;
            } 
          
            else {
                prev->next = curr->next;
            }

            // Move to the next node
            curr = curr->next;

        } 
      
         else {
           
            // Move pointers one position ahead
            prev = curr;
            curr = curr->next;
        }
    }

    return head;
}

void printList(struct Node* curr) {
    while (curr != NULL) {
        printf(" %d", curr->data);
        curr = curr->next;
    }
}

struct Node* createNode(int new_data) {
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    return new_node;
}

int main() {

    // Create a hard-coded linked list:
    // 2 -> 2 -> 1 -> 8 -> 2 -> NULL
    struct Node* head = createNode(2);
    head->next = createNode(2);
    head->next->next = createNode(1);
    head->next->next->next = createNode(8);
    head->next->next->next->next = createNode(2);

    int key = 2;
    head = deleteOccurrences(head, key);
    printList(head);

    return 0;
}
Java
// Java program to delete all occurrences of a given key 
// in a linked list
class Node {
    int data;
    Node next;

    Node(int new_data) {
        data = new_data;
        next = null;
    }
}

// Given the head of a list, delete all occurrences of a 
// given key and return the new head of the list
public class GfG {

    static Node deleteOccurrences(Node head, int key) {
        
        // Initialize pointers to traverse the linked list
        Node curr = head, prev = null;

        // Traverse the list to delete all occurrences
        while (curr != null) {

            // If current node's data is equal to key
            if (curr.data == key) {

                // If node to be deleted is head node
                if (prev == null) {
                    head = curr.next;
                } 
              
                else {
                    prev.next = curr.next;
                }

                // Move to the next node
                curr = curr.next;

            } 
          
             else {
               
                // Move pointers one position ahead
                prev = curr;
                curr = curr.next;
            }
        }

        return head;
    }

    // This function prints the contents of the linked list 
    // starting from the head
    static void printList(Node curr) {
        while (curr != null) {
            System.out.print(" " + curr.data);
            curr = curr.next;
        }
    }

    public static void main(String[] args) {

        // Create a hard-coded linked list:
        // 2 -> 2 -> 1 -> 8 -> 2 -> NULL
        Node head = new Node(2);
        head.next = new Node(2);
        head.next.next = new Node(1);
        head.next.next.next = new Node(8);
        head.next.next.next.next = new Node(2);

        int key = 2;

        head = deleteOccurrences(head, key);
        printList(head);
    }
}
Python
# Python program to delete all occurrences of a given key 
# in a singly linked list
class Node:
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

# Given the head of a list, delete all occurrences of a 
# given key and return the new head of the list
def delete_occurrences(head, key):

    # Initialize pointers to traverse the linked list
    curr = head
    prev = None

    # Traverse the list to delete all occurrences
    while curr is not None:

        # If current node's data is equal to key
        if curr.data == key:

            # If node to be deleted is head node
            if prev is None:
                head = curr.next
            else:
                prev.next = curr.next

            # Move to the next node
            curr = curr.next

        else:
            # Move pointers one position ahead
            prev = curr
            curr = curr.next

    return head

def print_list(curr):
    while curr is not None:
        print(f" {curr.data}", end="")
        curr = curr.next
    print()

if __name__ == "__main__":

    # Create a hard-coded linked list:
    # 2 -> 2 -> 1 -> 8 -> 2 -> None
    head = Node(2)
    head.next = Node(2)
    head.next.next = Node(1)
    head.next.next.next = Node(8)
    head.next.next.next.next = Node(2)

    key = 2
    head = delete_occurrences(head, key)
    print_list(head)
C#
// C# program to delete all occurrences of a given key 
// in a singly linked list
using System;

class Node {
    public int Data;
    public Node next;

    public Node(int newData) {
        Data = newData;
        next = null;
    }
}

class GfG {
  
   // Function to delete all occurrences of a 
   // given key and return the new head of the list
    static Node DeleteOccurrences(Node head, int key) {
        
        // Initialize pointers to traverse the linked list
        Node curr = head;
        Node prev = null;

        // Traverse the list to delete all occurrences
        while (curr != null) {

            // If current node's data is equal to key
            if (curr.Data == key) {

                // If node to be deleted is head node
                if (prev == null) {
                    head = curr.next;
                } 
           
                else {
                    prev.next = curr.next;
                }

                // Move to the next node
                curr = curr.next;

            } 
          
            else {
              
                // Move pointers one position ahead
                prev = curr;
                curr = curr.next;
            }
        }

        return head;
    }

    static void PrintList(Node curr) {
        while (curr != null) {
            Console.Write(" " + curr.Data);
            curr = curr.next;
        }
        Console.WriteLine();
    }

    static void Main() {
         
        // Create a hard-coded linked list:
        // 2 -> 2 -> 1 -> 8 -> 2 -> NULL
        Node head = new Node(2);
        head.next = new Node(2);
        head.next.next = new Node(1);
        head.next.next.next = new Node(8);
        head.next.next.next.next = new Node(2);

        int key = 2;
        head = DeleteOccurrences(head, key);
        PrintList(head);
    }
}
JavaScript
// JavaScript program to delete all occurrences of a given key 
// in a singly linked list
class Node {
    constructor(newData) {
        this.data = newData;
        this.next = null;
    }
}

// Given the head of a list, delete all occurrences of a given 
// key and return the new head of the list
function deleteOccurrences(head, key) {

    // Initialize pointers to traverse the linked list
    let curr = head;
    let prev = null;

    // Traverse the list to delete all occurrences
    while (curr !== null) {

        // If current node's data is equal to key
        if (curr.data === key) {

            // If node to be deleted is head node
            if (prev === null) {
                head = curr.next;
            } 
            
            else {
                prev.next = curr.next;
            }

            // Move to the next node
            curr = curr.next;

        } 
        
        else {
        
            // Move pointers one position ahead
            prev = curr;
            curr = curr.next;
        }
    }

    return head;
}

function printList(curr) {
    while (curr !== null) {
        console.log(" " + curr.data);
        curr = curr.next;
    }
    console.log();
}

// Create a hard-coded linked list:
// 2 -> 2 -> 1 -> 8 -> 2 -> NULL
let head = new Node(2);
head.next = new Node(2);
head.next.next = new Node(1);
head.next.next.next = new Node(8);
head.next.next.next.next = new Node(2);

let key = 2;
head = deleteOccurrences(head, key);
printList(head);

Output
 1 8

Time complexity: O(n), where n is the number of nodes in the list.
Auxiliary Space: O(1)
 



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 == x next = current->next deleteNode(head_ref, cur
14 min read
Delete multiple occurrences of key in Linked list using double pointer
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 occurrence
6 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 -> 5. Input: head1 = 3 -> 6 -> 9 -> 8 -
9 min read
Remove all continuous occurrences of 'a' and all occurrences of 'b'
Given a string str, the task is to remove all the continuous occurrences of a and all occurrences of b and print the resultant string. Examples Input: str = "abcddabcddddabbbaaaaaa" Output: acddacdddda 'abcddabcddddabbbaaaaaa' will not result in 'acddacddddaa' because after removing the required occurrences, the string will become 'acddacddddaa' wh
10 min read
Count occurrences of one linked list in another Linked List
Given two linked lists head1 and head2, the task is to find occurrences of head2 in head1. Examples: Input: Head1 = 1->2->3->2->4->5->2->4, Head2 = 2->4Output: Occurrences of head2 in head1: 2 Input: Head1 = 3->4->1->5->2, Head2 = 3->4Output: Occurrences of Head2 in Head1: 1 Approach 1: To solve the problem us
15 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 of 2. But as per the question we need to delete the
10 min read
Javascript Program For Moving 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 -> 6 -> 3 -> 10 key = 6 Output : 7 ->
6 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 -> 6 -> 3 -> 10 key = 6 Output : 7 ->
15+ 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 : empty List Note that this is different from Remove Dup
10 min read
Javascript Program For Removing 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->53Output: 23->35Input: 11->11->11->11->75->75Output: empty ListNote that this is different from Remove Duplicates
3 min read
Delete all the nodes from the doubly linked list that are greater than a given value
Given a doubly linked list containing N nodes and a number X, the task is to delete all the nodes from the list that are greater than the given value X. Examples: Input: 10 8 4 11 9, X = 9 Output: 8 4 9 Explanation: 10 and 11 are greater than 9. So after removing them doubly linked list will become 8 4 9. Input: 4 4 2 1 3 5, X = 2 Output: 2 1 Appro
11 min read
Delete all the nodes from a doubly linked list that are smaller than a given value
Given a doubly linked list containing N nodes and a number K, the task is to delete all the nodes from the list that are smaller than the given value K. Examples: Input: 15 <=> 16 <=> 10 <=> 9 <=> 6 <=> 7 <=> 17 K = 10 Output: 15 <=> 16 <=> 10 <=> 17 Input: 5 <=> 3 <=> 6 <=> 8
13 min read
Delete a given node in Linked List under given constraints
Given a Singly Linked List, write a function to delete a given node. Your function must follow following constraints: 1) It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to head node is not global. 2) It should not return a pointer to the head node. 3) It should not acc
11 min read
Delete all Prime Nodes from a Singly Linked List
Given a singly linked list containing N nodes, the task is to delete all nodes from the list which are prime.Examples: Input : List = 15 -> 16 -> 6 -> 7 -> 17 Output : Final List = 15 -> 16 -> 6Input : List = 15 -> 3 -> 4 -> 2 -> 9 Output :Final List = 15 ->4 -> 9 Approach: The idea is to traverse the nodes of th
12 min read
Delete all the even nodes from a Doubly Linked List
Given a doubly linked list containing N nodes, the task is to delete all the even nodes from the list. Examples: Input: Initial List = 15 <=> 16 <=> 6 <=> 7 <=> 17 Output: Final List = 15 <=> 7 <=> 17Explanation: 16 and 6 are even nodes. So we need to delete them. Input: Initial List = 5 <=> 3 <=> 6
11 min read
Delete all Prime Nodes from a Doubly Linked List
Given a doubly linked list containing N nodes, the task is to delete all nodes from the list which are prime. Examples: Input: List = 15 <=> 16 <=> 6 <=> 7 <=> 17 Output: Final List = 15 <=> 16 <=> 6 Input: List = 5 <=> 3 <=> 4 <=> 2 <=> 9 Output: Final List = 5 <=> 4 <=> 9 App
13 min read
Delete all nodes from the doubly linked list which are divisible by K
Given a doubly-linked list containing N nodes, the task is to delete all nodes from the list which are divisible by K. Examples: Input: List = 15 <=> 16 <=> 6 <=> 7 <=> 17, K = 2 Output: Final List = 15 <=> 7 <=> 17 Input: List = 5 <=> 3 <=> 4 <=> 2 <=> 9, K = 3 Output: Final List = 5 <
11 min read
Delete all the even nodes of a Circular Linked List
Given a circular singly linked list containing N nodes, the task is to delete all the even nodes from the list. Examples: Input : 57->11->2->56->12->61 Output : List after deletion : 57 -> 11 -> 61 Input : 9->11->32->6->13->20 Output : List after deletion : 9 -> 11 -> 13 The idea is to traverse the nodes of
10 min read
Delete all Prime Nodes from a Circular Singly Linked List
Given a circular singly linked list containing N nodes. The task is to delete all nodes from the list which are prime. Examples: Input : 9->11->32->6->13->20 Output : 9 32 6 20 Input : 6->11->16->21->17->10 Output : 6 16 21 10 Approach: The idea is to traverse the nodes of the circular singly linked list one by one and
13 min read
Delete all odd or even positioned nodes from Circular Linked List
Delete all odd or even position nodes from circular linked list Given a Singly Circular Linked List, starting from the first node delete all odd position nodes in it. Note: Linked list is considered to have 1-based indexing. That is, first element in the linked list is at position 1. Examples: Input : List = 99->11->22->33 Output : 11->
15+ min read
Delete all odd nodes of a Circular Linked List
Prerequisite: Delete all the even nodes of a Circular Linked ListGiven a circular singly linked list containing N nodes, the task is to delete all the odd nodes from the list. Examples: Input: 572->112->21->5->1->6 Output: 572 -> 112 -> 6 Explanation: All the odd valued nodes have been deletedInput: 9->11->32->6->13
10 min read
Program to delete all even nodes from a Singly Linked List
Given a singly linked list containing N nodes, the task is to delete all the even nodes from the list. Examples: Input: LL = 1 -> 4 -> 3 -> 18 -> 19 Output: 1 -> 3 -> 19Input: LL = 5 -> 3 -> 6 -> 8 -> 4 -> 1 -> 2 -> 9 Output: 5 -> 3 -> 1 -> 9 Approach 1: The idea is to traverse the nodes of the singly
15+ min read
Skip List - Efficient Search, Insert and Delete in Linked List
A skip list is a data structure that allows for efficient search, insertion and deletion of elements in a sorted list. It is a probabilistic data structure, meaning that its average time complexity is determined through a probabilistic analysis. In a skip list, elements are organized in layers, with each layer having a smaller number of elements th
6 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 -> 1Explanation: Given Linked List: 1 -> 2 -> 7 -
10 min read
Count Occurrences in a Linked List
Given a singly linked list and a key, the task is to count the number of occurrences of the given key in the linked list. Example : Input : head: 1->2->1->2->1->3->1 , key = 1Output : 4 Explanation: key equals 1 has 4 occurrences. Input : head: 1->2->1->2->1, key = 3Output : 0Explanation: key equals to 3 has 0 occurren
9 min read
Delete continuous nodes with sum K from a given linked list
Given a singly linked list and an integer K, the task is to remove all the continuous set of nodes whose sum is K from the given linked list. Print the updated linked list after the removal. If no such deletion can occur, print the original Linked list. Examples: Input: Linked List: 1 -> 2 -> -3 -> 3 -> 1, K = 3 Output: -3 -> 1 Expla
11 min read
Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
Given a pointer to a node to be deleted, delete the node. Note that we don't have a pointer to the head node. Recommended PracticeDelete nodes having greater value on rightTry It!A simple solution is to traverse the linked list until you find the node you want to delete. But this solution requires a pointer to the head node, which contradicts the p
8 min read
Delete Nth node from the end of the given linked list
Given a linked list and an integer N, the task is to delete the Nth node from the end of the given linked list. Examples: Input: 2 -> 3 -> 1 -> 7 -> NULL, N = 1 Output: The created linked list is: 2 3 1 7 The linked list after deletion is: 2 3 1 Input: 1 -> 2 -> 3 -> 4 -> NULL, N = 4 Output: The created linked list is: 1 2 3
13 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<->3 Input: LinkedList: 1<->2<->3, pos = 1Output: LinkedList: 2<->3 To delete a node at a specific position in dou
9 min read
Delete a Linked List node at a given position
Given a singly linked list and a position (1-based indexing), the task is to delete a linked list node at the given position. Note: Position will be valid (i.e, 1 <= position <= linked list length) Example: Input: position = 2, Linked List = 8->2->3->1->7Output: Linked List = 8->3->1->7 Input: position = 1, Linked List =
8 min read
Article Tags :
Practice Tags :