Delete multiple occurrences of key in Linked list using double pointer
Last Updated :
10 Jan, 2024
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++
- Java
- Python3
- C#
- Javascript
C++
#include <iostream>
using namespace std;
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)
{
struct Node** pp = &head;
while (*pp) {
struct Node* entry = *pp;
if (entry->data == key) {
*pp = entry->next;
delete (entry);
}
else
pp = &(entry->next);
}
}
int main()
{
push(2);
push(2);
push(4);
push(3);
push(2);
int key = 2;
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 (entry.data == key) {
if (prev != null ) {
prev.next = entry.next;
} else {
head = entry.next;
}
} else {
prev = entry;
}
pp = entry.next;
}
}
public static void main(String[] args) {
push( 2 );
push( 2 );
push( 4 );
push( 3 );
push( 2 );
int key = 2 ;
System.out.println( "Created Linked List:" );
printList(head);
System.out.println( "\nLinked List after Deletion of 2:" );
deleteEntry(key);
printList(head);
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
def printList(node):
while node:
print (node.data, end = " " )
node = node. next
print ()
def push(new_data):
new_node = Node(new_data)
new_node. next = head
globals ()[ 'head' ] = new_node
def delete_entry(key):
global head
entry = head
prev = None
while entry:
if entry.data = = key:
if prev:
prev. next = entry. next
else :
head = entry. next
del entry
entry = prev. next if prev else head
else :
prev = entry
entry = entry. next
if __name__ = = '__main__' :
head = None
push( 2 )
push( 2 )
push( 4 )
push( 3 )
push( 2 )
key = 2
print ( "Created Linked List:" )
printList(head)
print ( "\nLinked List after Deletion of 2:" )
delete_entry(key)
printList(head)
|
C#
using System;
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)
{
Node pp = head;
Node prev = null ;
while (pp != null )
{
if (pp.data == key)
{
if (prev != null )
{
prev.next = pp.next;
}
else
{
head = pp.next;
}
pp = pp.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;
Console.WriteLine( "Created Linked List: " );
PrintList(head);
Console.WriteLine();
DeleteEntry(key);
Console.WriteLine( "Linked List after Deletion of 2: " );
PrintList(head);
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .next = null ;
}
}
let head = null ;
function printList(node) {
while (node !== null ) {
console.log(` ${node.data} `);
node = node.next;
}
}
function push(new_data) {
const new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
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;
}
}
}
push(2);
push(2);
push(4);
push(3);
push(2);
console.log( "Created Linked List: " );
printList(head);
console.log( "\n" );
const keyToDelete = 2;
deleteEntry(keyToDelete);
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