×

Remove duplicates from an unsorted Linked List

Remove duplicates from an unsorted Linked List

This article will explain how we can remove duplicates from unsorted linked lists. Here we have given an unsorted singly linked list and will remove duplicates from the given linked list.

Example:  Ifthe given linked list is 4 -> 1 -> 1 -> 5 -> 2 then the output will be 4 -> 1 -> 5 -> 2.

Here, we will see the ways to remove duplicates from the linked list.

Method 1: Using 2 - Loops

This method will use two loops to remove duplicates. The first loop will pick the linked list elements one by one, and the second loop will compare the picked element with other elements of the linked list.

Source code to implement method 1 in C language:

 #include<stdio.h>
 #include<stdlib.h>
 struct node
 {
 int info;
 struct node *next;
 };
 struct node *start = NULL;
 // For inserting the elements in the linked list
 void add(int item)
 {
 struct node *t, *p;
 t = (struct node *)malloc( sizeof( struct node ));
 if(start == NULL)
 {
 start = t;
 start -> info = item;
 start -> next = NULL;
 return;
 }
 else
 {
 struct node *p = start;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // For removing the duplicated from the linked list
 void removeDuplicates(struct node * t)
 {
     struct node *p1, *p2, *temp;
     p1 = t;
     /* Pick elements one by one */
     while (p1 != NULL && p1->next != NULL)
     {
         p2 = p1;
         while (p2->next != NULL)
         {
             if (p1->info == p2->next->info)
             {
                 temp = p2->next;
                 p2->next = p2->next->next;
             }
             else
                 p2 = p2->next;
         }
         p1 = p1->next;
     }
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
                                     }
                                     while(t -> next != NULL)
                                     {
                         printf("%d -> ",t -> info);
                         t = t -> next;
                         }
                         printf("%d",t -> info);
 }
 // Driver Function
 int main()
 {
         add(10);
         add(4);
         add(2);
         add(9);
         add(2);
     removeDuplicates(start);
     traverse(start);
     return 0;
 } 

Output: -

Remove duplicates from an unsorted Linked List

Time Complexity: O(n^2)

Method 2: Using Hashing

This method will use the HashSet to remove duplicates. It will first traverse the linked list from head to tail and check every element of the linked list whether it is present in the HashSet or not. If it finds duplicates, we remove them. Otherwise, it will put them into the HashSet.

Source code to implement method 2 in Java:

 import java.util.*;
 public class removeDuplicates
 {
     static class Node
     {
         int data;
         Node next;
         public Node(int data)
         {
             this.data = data;
              next = null;
         }
     }
     /* Function to remove duplicates from an unsorted linked list */
     static void removeDuplicate(Node head)
     {
         // Hash to store seen values
         HashSet<Integer> hs = new HashSet<>();
         /* Pick elements one by one */
         Node temp = head;
         Node prev = null;
         while (temp != null)
         {
             int v = temp.data;
             if (hs.contains(v)) {
                 prev.next = temp.next;
             }
             else
             {
                 hs.add(v);
                 prev = temp;
             }
             temp = temp.next;
         }
     }
     /* Function to print nodes in a given linked list */
     static void traverse(Node head)
     {
         while (head != null)
         {
             System.out.print(head.data + " ");
             head = head.next;
         }
     }
     public static void main(String[] args)
     {
             Scanner sc = new Scanner(System.in);
             System.out.println("Enter the total no of elements");
             int t = sc.nextInt();
            int a1= sc.nextInt();
             Node head= new Node(a1);
             Node tail = head;
             for (int i = 1; i < t; i++)
             {
                         int a = sc.nextInt();
                         tail.next = (new Node(a));
                         tail = tail.next;
             }
         System.out.println("Linked list before removing duplicates :");
         traverse(head);
         removeDuplicate(head);
         System.out.println("\nLinked list after removing duplicates :");
         traverse(head);
     }
 } 

Output: -

Remove duplicates from an unsorted Linked List

Time Complexity: O(n)


Related Topics

Complete Binary tree

In this article, we will discuss the complete binary tree. But before start discussing the complete binary tree, we should first see a brief description of a binary tree. What is...

7 minutes read.

Counting Sort

Counting Sort: Counting sort is a sorting algorithm that is used to sort the elements of the array within a specific range. It counts the same element number of the...

3 minutes read.

Implementation of Queue

Implementation of queue: We can implement the queue through the array and linked list. An array is the easiest way to implement the queue. When a queue is created with the...

7 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Right side view of binary tree

The right view of the binary tree is generally known to be that side viewed from the right direction of the point of view. To be more precise, the right-side...

8 minutes read.

B Tree vs B + Tree: Data Structure

Difference Between B Tree and B+ Tree What is B Tree? B-Tree is a self-balancing or special type of m-way tree. B-Trees are used mainly in disc access. If we want...

3 minutes read.

Stack vs Queue: Data Structure

 Difference Between Stack and Queue What is Stack? The LIFO principle applies on insertion and deletion operations of the stack which means last inserted element to the stack will remove first....

3 minutes read.

Difference between Structured and Object-Oriented Analysis

Analysis means observing and collecting relevant information about the structure of something or the basic details of a system's requirements. Structured and Object Oriented Analysis are both widely used in...

2 minutes read.

Hashing

Hashing: Hashing is a process in which a large amount of data is mapped to a small table with the help of hashing function. It is a searching technique. Hash table We...

4 minutes read.

Properties of Binary Tree

Trees are maybe of the most significant datum structures. They are used to store and figure out data. A binarytree is a tree data structure made from nodes, all of which has...

3 minutes read.

Compare Balanced Binary Tree and Complete Binary Tree

Complete and balanced binary trees are important and general topics in the concept – Tree data structure. Before discussing the complete and balanced binary tree, we need to have an...

8 minutes read.

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

Difference Between Linear and Non Linear Data Structures

Data Structure A data structure is a data object together with the relationships between the instances and the individual elements that compose an instance. These relationships are defined by the operations...

5 minutes read.

Write Main Difference Between Tree and Graph in Data Structures

Graph: The graph has two sets, which are considered V and E. These vertices are also called nodes, and edges are referred to as arcs connecting any two nodes in a...

4 minutes read.

Bitwise Operators and their Important Tricks

In most of the programs you write today, you deal with data types comprising bytes, such as integer, float, double, etc. Dealing with bytes? It is a quite normal task,...

5 minutes read.

Print kth least significant bit number

You have given a number and you have to find out the kth least significant bit of this number. K will be given to you.  The bit will be from...

3 minutes read.

Structure and Union Data Structure

The array is used for the same type of data, but if we want to store a mixed type of data in a group, then the array cannot be used. The Structure...

4 minutes read.

Binary Tree in Data Structures

What is a Binary Tree in Data Structures? The term binary itself means bi, which implies two of anything. So very clearly, we know we present the trees in the form...

6 minutes read.

Depth of binary tree

We all know that a binary tree is a kind of tree that helps us maintain the order and balance of the tree. It is a type of tree in...

4 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.