×

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

Delete N nodes after M nodes of a linked list

Delete N nodes after M nodes of a linked list In this problem, we have given a linked list and two integers M and N. We need to traverse the linked...

3 minutes read.

Data structure: Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

What is the difference between DFS and BFS?

What is BFS? BFS is generally known as the low level traversal. As we already know that it stands for breadth first search and is mainly used in the queue data...

4 minutes read.

Breadth First Search

Breadth First Search Breadth first search is a graph traversing algorithm. In this, we start traversing from the source node or any selected node and traverse the graph layer by layer....

6 minutes read.

Buffer overflow attack with examples

You have undoubtedly faced the term buffer overflow in your programming journey. Many times it occurs when we try to run a piece of code with user input, but it...

4 minutes read.

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...

3 minutes read.

Given a Binary Tree Return All Root-to-Leaf Paths

Implementation #include <bits/stdc++.h> using namespace std; // A binary tree node generally consists of data, a pointer to the left and right child, and a pointer to the right child.  class __nod { public: int record; __nod* Lft; __nod*...

9 minutes read.

Spanning Tree

Spanning Tree: The spanning tree is a subset of the graph. It is a non-cyclic graph. If any node in the spanning tree is truncated, the entire graph fails. There are...

10 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.

Finding the Sum of All Paths in a Binary Tree

Implementation // Writing the C++ program to implement the below approach.  #include <bits/stdc++.h> using namespace std; // creating the new tree node structure. struct Tree__nod { int val; Tree__nod *Lft, *Rt; }; // creating a new function that will...

8 minutes read.

Arrange consonants and vowels nodes in a linked list

Arrange consonants and vowels nodes in a linked list In this problem, we have given a singly linked list. Here we will arrange the consonants and vowels nodes of the list...

2 minutes read.

Introduction to 1D-Arrays

One Dimensional Array Technical Definitions The simplest version of an Array is a One-Dimensional Array, in which the items are stored linearly and may be accessed individually by supplying the index value...

6 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Deletion Operation from A B Tree

This article will show the deletion operation through the b tree in C++ programming language. Implementation #include <iostream> using namespace std; class B_TreeNod {   int *kys;   int m;   BTreeNod **C;   int j;   bool leaf;  ...

5 minutes read.

Reverse the Singly Linked List in C

Reverse the Singly Linked List in C This article has given a singly linked list and will reverse the linked list by changing the links between nodes. Example:                         Input:  2 -> 4...

3 minutes read.

Binary Tree Uses

A binary tree is a tree data structure containing hubs with at most two children for instance a right and left child. The node at the top is insinuated as the...

3 minutes read.

Operations of B Tree in C++ Language

B tree tends to be a self-aligning and balancing tree that helps us organise our data and document safely. We know that every data or information in the B tree...

9 minutes read.

Hash Table vs STL Map

Hash table and STL map are extremely valuable information structures in software engineering. Here we will consider the examination between their properties to be well as execution.  To start with, we will...

7 minutes read.

String Operations in Data Structures

Operations on Strings Reversing the order of words in a sentence Reversing a string is a technique that reverses or alters the order of a given string so that the last character...

9 minutes read.

Queue Data Structure

Queue in DS: The queue is a non-primitive and linear data structure. It works on the principle of FIFO (First In First Out). That is, the element that is added...

4 minutes read.