Skip to content
Related Articles

Related Articles

C# Program For Removing Duplicates From An Unsorted Linked List

Improve Article
Save Article
Like Article
  • Last Updated : 14 Dec, 2021

Write a removeDuplicates() function that takes a list and deletes any duplicate nodes from the list. The list is not sorted. 
For example if the linked list is 12->11->12->21->41->43->21 then removeDuplicates() should convert the list to 12->11->21->41->43.

METHOD 1 (Using two loops): 
This is the simple way where two loops are used. Outer loop is used to pick the elements one by one and the inner loop compares the picked element with the rest of the elements. 
Thanks to Gaurav Saxena for his help in writing this code.

C#




// C# program to remove duplicates from
// unsorted linked list
using System;
class List_ 
{
    Node head;
    class Node 
    {
        public int data;
        public Node next;
        public Node(int d)
        {
            data = d;
            next = null;
        }
    }
  
    /* Function to remove duplicates from
       an unsorted linked list */
    void remove_duplicates()
    {
        Node ptr1 = null
             ptr2 = null, dup = null;
        ptr1 = head;
  
        // Pick elements one by one 
        while (ptr1 != null && 
               ptr1.next != null
        {
            ptr2 = ptr1;
  
            /* Compare the picked element with 
               rest of the elements */
            while (ptr2.next != null
            {
                // If duplicate then delete it 
                if (ptr1.data == ptr2.next.data) 
                {
                    // sequence of steps is important here
                    dup = ptr2.next;
                    ptr2.next = ptr2.next.next;
                }
                else
                {
                    ptr2 = ptr2.next;
                }
            }
            ptr1 = ptr1.next;
        }
    }
  
    void printList(Node node)
    {
        while (node != null
        {
            Console.Write(node.data + " ");
            node = node.next;
        }
    }
  
    // Driver Code
    public static void Main(String[] args)
    {
        List_ list = new List_();
        list.head = new Node(10);
        list.head.next = new Node(12);
        list.head.next.next = new Node(11);
        list.head.next.next.next = new Node(11);
        list.head.next.next.next.next = new Node(12);
        list.head.next.next.next.next.next = new Node(11);
        list.head.next.next.next.next.next.next
            = new Node(10);
  
        Console.WriteLine(
                "Linked List_ before removing duplicates : ");
        list.printList(list.head);
  
        list.remove_duplicates();
        Console.WriteLine("");
        Console.WriteLine(
                "Linked List_ after removing duplicates : ");
        list.printList(list.head);
    }
}
// This code is contributed by gauravrajput1


Output: 

Linked list before removing duplicates:
10 12 11 11 12 11 10 
Linked list after removing duplicates:
10 12 11

Time Complexity: O(n^2)

METHOD 2 (Use Sorting): 
In general, Merge Sort is the best-suited sorting algorithm for sorting linked lists efficiently. 
1) Sort the elements using Merge Sort. We will soon be writing a post about sorting a linked list. O(nLogn) 
2) Remove duplicates in linear time using the algorithm for removing duplicates in sorted Linked List. O(n) 
Please note that this method doesn’t preserve the original order of elements.
Time Complexity: O(nLogn)

METHOD 3 (Use Hashing): 
We traverse the link list from head to end. For every newly encountered element, we check whether it is in the hash table: if yes, we remove it; otherwise we put it in the hash table.

C#




// C# program to remove duplicates
// from unsorted linkedlist
using System;
using System.Collections.Generic;
  
class removeDuplicates
{
    class node 
    {
        public int val;
        public node next;
  
        public node(int val) 
        {
            this.val = val;
        }
}
  
// Function to remove duplicates from a
// unsorted linked list 
static void removeDuplicate(node head) 
{    
    // Hash to store seen values
    HashSet<int> hs = new HashSet<int>();
  
    // Pick elements one by one 
    node current = head;
    node prev = null;
    while (current != null
    {
        int curval = current.val;
          
        // If current value is seen before
        if (hs.Contains(curval))
        {
            prev.next = current.next;
        }
        else 
        {
            hs.Add(curval);
            prev = current;
        }
        current = current.next;
    }
}
  
// Function to print nodes in a 
// given linked list 
static void printList(node head) 
{
    while (head != null
    {
        Console.Write(head.val + " ");
        head = head.next;
    }
}
  
// Driver code
public static void Main(String[] args) 
{   
    // The constructed linked list is:
    // 10->12->11->11->12->11->10
    node start = new node(10);
    start.next = new node(12);
    start.next.next = new node(11);
    start.next.next.next = new node(11);
    start.next.next.next.next = new node(12);
    start.next.next.next.next.next = new node(11);
    start.next.next.next.next.next.next = new node(10);
  
    Console.WriteLine("Linked list before removing " +
                      "duplicates :");
    printList(start);
    removeDuplicate(start);
  
    Console.WriteLine("Linked list after removing "
                      "duplicates :");
    printList(start);
}
}
// This code is contributed by amal kumar choubey


Output: 

Linked list before removing duplicates:
10 12 11 11 12 11 10 
Linked list after removing duplicates:
10 12 11

Thanks to bearwang for suggesting this method.
Time Complexity: O(n) on average (assuming that hash table access time is O(1) on average).

Please refer complete article on Remove duplicates from an unsorted linked list for more details!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!