Remove duplicates from a linked list

Last Updated : 10 Aug, 2026

Given a head of an unsorted linked list. Remove duplicate elements from this unsorted Linked List. When a value appears in multiple nodes, the node which appeared first should be kept, all other duplicates are to be removed.

Examples:

Input: head = 5 -> 2 -> 2 -> 4
Output: 5 -> 2 -> 4
Explanation: Given linked list elements are 5 -> 2 -> 2 -> 4, in which 2 is repeated only. So, we will delete the extra repeated elements 2 from the linked list and the resultant linked list will contain 5->2->4.

1


Input: head = 2 -> 2 -> 2 -> 2 -> 2
Output: 2
Explanation: Given linked list elements are 2 -> 2 -> 2 -> 2 -> 2, in which 2 is repeated. So, we will delete the extra repeated elements 2 from the linked list and the resultant linked list will contain only 2.

2
Try It Yourself
redirect icon

[Naive Approach] Check Every Previous Node - O(n ^ 2) Time and O(1) Space

The idea is to traverse the linked list and, for every node, check all the previous nodes to see whether the current value has already appeared. If it is found, remove the current node; otherwise, keep it.

Working of Approach:

  • Traverse the linked list using the current node.
  • For each node, traverse from the head to the current node.
  • If the current value is found earlier, delete the current node.
  • Otherwise, move to the next node.
  • Return the modified linked list.
C++
#include <iostream>
using namespace std;

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

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

// Function to remove duplicate nodes.
Node *removeDuplicates(Node *head)
{

    // Return if the list is empty.
    if (head == nullptr)
        return head;

    Node *prev = head;
    Node *curr = head->next;

    // Traverse the linked list.
    while (curr != nullptr)
    {

        bool duplicate = false;

        // Check all previous nodes.
        Node *temp = head;
        while (temp != curr)
        {
            if (temp->data == curr->data)
            {
                duplicate = true;
                break;
            }
            temp = temp->next;
        }

        // Remove duplicate node.
        if (duplicate)
        {
            prev->next = curr->next;
            delete curr;
            curr = prev->next;
        }
        else
        {
            prev = curr;
            curr = curr->next;
        }
    }

    return head;
}

// Function to print linked list.
void printList(Node *head)
{
    while (head)
    {
        cout << head->data;
        if (head->next)
            cout << " -> ";
        head = head->next;
    }
    cout << endl;
}

int main()
{

    // Creating linked list:
    // 5 -> 2 -> 2 -> 4
    Node *head = new Node(5);
    head->next = new Node(2);
    head->next->next = new Node(2);
    head->next->next->next = new Node(4);

    head = removeDuplicates(head);

    printList(head);

    return 0;
}
Java
import java.util.*;

class Node {
    public int data;
    public Node next;

    public Node(int x)
    {
        data = x;
        next = null;
    }
}

public class GFG {
    // Function to remove duplicate nodes.
    public static Node removeDuplicates(Node head)
    {
        // Return if the list is empty.
        if (head == null)
            return head;

        Node prev = head;
        Node curr = head.next;

        // Traverse the linked list.
        while (curr != null) {
            boolean duplicate = false;

            // Check all previous nodes.
            Node temp = head;
            while (temp != curr) {
                if (temp.data == curr.data) {
                    duplicate = true;
                    break;
                }
                temp = temp.next;
            }

            // Remove duplicate node.
            if (duplicate) {
                prev.next = curr.next;
                curr = prev.next;
            }
            else {
                prev = curr;
                curr = curr.next;
            }
        }

        return head;
    }

    // Function to print linked list.
    public static void printList(Node head)
    {
        while (head != null) {
            System.out.print(head.data);
            if (head.next != null)
                System.out.print(" -> ");
            head = head.next;
        }
        System.out.println();
    }

    public static void main(String[] args)
    {
        // Creating linked list:
        // 5 -> 2 -> 2 -> 4
        Node head = new Node(5);
        head.next = new Node(2);
        head.next.next = new Node(2);
        head.next.next.next = new Node(4);

        head = removeDuplicates(head);

        printList(head);
    }
}
Python
class Node:
    # Constructor to initialize the node
    def __init__(self, x):
        self.data = x
        self.next = None

# Function to remove duplicate nodes.
def removeDuplicates(head):
    # Return if the list is empty.
    if head is None:
        return head

    prev = head
    curr = head.next

    # Traverse the linked list.
    while curr is not None:
        duplicate = False

        # Check all previous nodes.
        temp = head
        while temp != curr:
            if temp.data == curr.data:
                duplicate = True
                break
            temp = temp.next

        # Remove duplicate node.
        if duplicate:
            prev.next = curr.next
            curr = prev.next
        else:
            prev = curr
            curr = curr.next

    return head

# Function to print linked list.
def printList(head):
    while head is not None:
        print(head.data, end="")
        if head.next is not None:
            print(" -> ", end="")
        head = head.next
    print()


if __name__ == '__main__':
    # Creating linked list:
    # 5 -> 2 -> 2 -> 4
    head = Node(5)
    head.next = Node(2)
    head.next.next = Node(2)
    head.next.next.next = Node(4)

    head = removeDuplicates(head)

    printList(head)
C#
using System;

class Node {
    public int data;
    public Node next;

    public Node(int x)
    {
        data = x;
        next = null;
    }
}

class GFG {
    // Function to remove duplicate nodes.
    static Node removeDuplicates(Node head)
    {
        // Return if the list is empty.
        if (head == null)
            return head;

        Node prev = head;
        Node curr = head.next;

        // Traverse the linked list.
        while (curr != null) {
            bool duplicate = false;

            // Check all previous nodes.
            Node temp = head;
            while (temp != curr) {
                if (temp.data == curr.data) {
                    duplicate = true;
                    break;
                }
                temp = temp.next;
            }

            // Remove duplicate node.
            if (duplicate) {
                prev.next = curr.next;
                curr = prev.next;
            }
            else {
                prev = curr;
                curr = curr.next;
            }
        }

        return head;
    }

    // Function to print linked list.
    static void printList(Node head)
    {
        while (head != null) {
            Console.Write(head.data);
            if (head.next != null)
                Console.Write(" -> ");
            head = head.next;
        }
        Console.WriteLine();
    }

    static void Main(string[] args)
    {
        // Creating linked list:
        // 5 -> 2 -> 2 -> 4
        Node head = new Node(5);
        head.next = new Node(2);
        head.next.next = new Node(2);
        head.next.next.next = new Node(4);

        head = removeDuplicates(head);

        printList(head);
    }
}
JavaScript
class Node {
    constructor(x)
    {
        this.data = x;
        this.next = null;
    }
}

// Function to remove duplicate nodes.
function removeDuplicates(head)
{
    // Return if the list is empty.
    if (head === null)
        return head;

    let prev = head;
    let curr = head.next;

    // Traverse the linked list.
    while (curr !== null) {
        let duplicate = false;

        // Check all previous nodes.
        let temp = head;
        while (temp !== curr) {
            if (temp.data === curr.data) {
                duplicate = true;
                break;
            }
            temp = temp.next;
        }

        // Remove duplicate node.
        if (duplicate) {
            prev.next = curr.next;
            curr = prev.next;
        }
        else {
            prev = curr;
            curr = curr.next;
        }
    }

    return head;
}

// Function to print linked list.
function printList(head)
{
    let output = "";
    while (head !== null) {
        output += head.data;
        if (head.next !== null)
            output += " -> ";
        head = head.next;
    }
    console.log(output);
}

// Driver Code

// Creating linked list:
// 5 -> 2 -> 2 -> 4
let head = new Node(5);
head.next = new Node(2);
head.next.next = new Node(2);
head.next.next.next = new Node(4);

head = removeDuplicates(head);

printList(head);

Output
5 -> 2 -> 4

[Expected Approach] Using Hash Set - O(n) Time and O(n) Space

The idea is to traverse the linked list while storing the values that have already been seen in a hash set. If the current node's value is already present in the set, it is a duplicate, so remove that node. Otherwise, insert the value into the set and continue traversing the list.

Working of Approach:

  • Create an empty hash set to store the values already encountered.
  • Traverse the linked list from the head node.
  • If the current node's value is not present in the hash set, insert it and move ahead.
  • If the value is already present, remove the current node by updating the previous node's next pointer.
  • Continue until all nodes are processed and return the modified linked list.

Let us understand with an example:
Input: head = 5 -> 2 -> 2 -> 4

  • Start with the linked list 5 -> 2 -> 2 -> 4 and an empty hash set { }. Insert 5 into the set and move to the next node.
  • Visit 2. Since it is not present in the hash set, insert it. The set becomes {5, 2}.
  • Visit the next 2. It is already present in the hash set, so it is a duplicate. Remove this node by updating the previous node's next pointer.
  • Move to 4. It is not present in the hash set, so insert it. The set becomes {5, 2, 4}.
  • The traversal ends, and the modified linked list is 5 -> 2 -> 4.
1
C++
#include <iostream>
using namespace std;

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

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

Node *removeDuplicates(Node *head)
{

    // Return if the linked list is empty.
    if (!head)
        return nullptr;

    // Using an unordered_set to keep track of seen values.
    unordered_set<int> seen;
    Node *curr = head;
    Node *prev = nullptr;

    // Iterating through the linked list.
    while (curr != nullptr)
    {

        // If the current value is a duplicate, remove the node.
        if (seen.find(curr->data) != seen.end())
        {
            prev->next = curr->next;
            delete curr;
        }
        else
        {

            // If the value is not a duplicate, add it to the set and update the
            // pointers.
            seen.insert(curr->data);
            prev = curr;
        }
        curr = prev->next;
    }
    return head;
}

// Function to print linked list.
void printList(Node *head)
{
    while (head)
    {
        cout << head->data;
        if (head->next)
            cout << " -> ";
        head = head->next;
    }
    cout << endl;
}

int main()
{

    // Creating linked list:
    // 5 -> 2 -> 2 -> 4
    Node *head = new Node(5);
    head->next = new Node(2);
    head->next->next = new Node(2);
    head->next->next->next = new Node(4);

    head = removeDuplicates(head);

    printList(head);

    return 0;
}
Java
import java.util.HashSet;

class Node {
    public int data;
    public Node next;

    public Node(int x)
    {
        data = x;
        next = null;
    }
}

public class GFG {
    public static Node removeDuplicates(Node head)
    {

        // Return if the linked list is empty.
        if (head == null)
            return null;

        // Using a HashSet to keep track of seen values.
        HashSet<Integer> seen = new HashSet<>();
        Node curr = head;
        Node prev = null;

        // Iterating through the linked list.
        while (curr != null) {

            // If the current value is a duplicate, remove
            // the node.
            if (seen.contains(curr.data)) {
                prev.next = curr.next;
                curr = prev.next;
            }
            else {

                // If the value is not a duplicate, add it
                // to the set and update the pointers.
                seen.add(curr.data);
                prev = curr;
            }
            curr = prev != null ? prev.next : null;
        }
        return head;
    }

    // Function to print linked list.
    public static void printList(Node head)
    {
        while (head != null) {
            System.out.print(head.data);
            if (head.next != null)
                System.out.print(" -> ");
            head = head.next;
        }
        System.out.println();
    }

    public static void main(String[] args)
    {

        // Creating linked list:
        // 5 -> 2 -> 2 -> 4
        Node head = new Node(5);
        head.next = new Node(2);
        head.next.next = new Node(2);
        head.next.next.next = new Node(4);

        head = removeDuplicates(head);

        printList(head);
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None


def removeDuplicates(head):

    # Return if the linked list is empty.
    if not head:
        return None

    # Using a set to keep track of seen values.
    seen = set()
    curr = head
    prev = None

    # Iterating through the linked list.
    while curr is not None:

        # If the current value is a duplicate, remove the node.
        if curr.data in seen:
            prev.next = curr.next
            curr = prev.next
        else:
            # If the value is not a duplicate, add it to the set and update the
            # pointers.
            seen.add(curr.data)
            prev = curr
        curr = prev.next if prev else None
    return head

# Function to print linked list.
def printList(head):
    while head is not None:
        print(head.data, end='')
        if head.next is not None:
            print(' -> ', end='')
        head = head.next
    print()


if __name__ == '__main__':

    # Creating linked list:
    # 5 -> 2 -> 2 -> 4
    head = Node(5)
    head.next = Node(2)
    head.next.next = Node(2)
    head.next.next.next = Node(4)

    head = removeDuplicates(head)

    printList(head)
C#
using System;
using System.Collections.Generic;

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

    public Node(int x)
    {
        data = x;
        next = null;
    }
}

public class GFG {
    public static Node removeDuplicates(Node head)
    {

        // Return if the linked list is empty.
        if (head == null)
            return null;

        // Using a HashSet to keep track of seen values.
        HashSet<int> seen = new HashSet<int>();
        Node curr = head;
        Node prev = null;

        // Iterating through the linked list.
        while (curr != null) {

            // If the current value is a duplicate, remove
            // the node.
            if (seen.Contains(curr.data)) {
                prev.next = curr.next;
                curr = prev.next;
            }
            else {
                // If the value is not a duplicate, add it
                // to the set and update the pointers.
                seen.Add(curr.data);
                prev = curr;
            }
            curr = prev != null ? prev.next : null;
        }
        return head;
    }

    // Function to print linked list.
    public static void printList(Node head)
    {
        while (head != null) {
            Console.Write(head.data);
            if (head.next != null)
                Console.Write(" -> ");
            head = head.next;
        }
        Console.WriteLine();
    }

    public static void Main()
    {

        // Creating linked list:
        // 5 -> 2 -> 2 -> 4
        Node head = new Node(5);
        head.next = new Node(2);
        head.next.next = new Node(2);
        head.next.next.next = new Node(4);

        head = removeDuplicates(head);

        printList(head);
    }
}
JavaScript
class Node {
    constructor(x)
    {
        this.data = x;
        this.next = null;
    }
}

function removeDuplicates(head)
{

    // Return if the linked list is empty.
    if (!head)
        return null;

    // Using a Set to keep track of seen values.
    let seen = new Set();
    let curr = head;
    let prev = null;

    // Iterating through the linked list.
    while (curr != null) {

        // If the current value is a duplicate, remove the
        // node.
        if (seen.has(curr.data)) {
            prev.next = curr.next;
            curr = prev.next;
        }
        else {
            // If the value is not a duplicate, add it to
            // the set and update the pointers.
            seen.add(curr.data);
            prev = curr;
        }
        curr = prev ? prev.next : null;
    }
    return head;
}

// Function to print linked list.
function printList(head)
{
    let current = head;
    while (current != null) {
        process.stdout.write(current.data.toString());
        if (current.next != null)
            process.stdout.write(" -> ");
        current = current.next;
    }
    console.log();
}

// Driver Code
let head = new Node(5);
head.next = new Node(2);
head.next.next = new Node(2);
head.next.next.next = new Node(4);

head = removeDuplicates(head);

printList(head);

Output
5 -> 2 -> 4
Comment