Open In App

Delete multiple occurrences of key in Linked list using double pointer

Improve
Improve
Like Article
Like
Save
Share
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 = 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:

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);


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


Last Updated : 10 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads