Saturday, February 22, 2020

how to remove duplicate records in the linked list?

the hackerrank post today challenge is to remove duplicate record from integer linklist.

i use hashset to store the unique integer from the linklist, if the current node data already exist in the hashset. i simply pointing the previous node to the current node next pointer. if not found, i add the current node data to the hashset and move to the next node.


here is the sample code in C#

using System;
using System.Collections.Generic;
class Node
{
public int data;
public Node next;
    public Node(int d){
        data=d;
        next=null;
    }
}
class Solution {
  public static Node removeDuplicates(Node head){
    //Write your code here
    if (head==null){
        return null;
    }
    HashSet<int> hashset =new HashSet<int>();
    Node prevNode = head;
    Node currentNode =prevNode.next;
    if(currentNode==null){
        return head;
    }
    hashset.Add(prevNode.data);
    while(currentNode!=null)
        {
        if(hashset.Contains(currentNode.data))
            {
            prevNode.next=currentNode.next;
            currentNode=currentNode.next;
        }
        else{
            hashset.Add(currentNode.data);
              prevNode=currentNode;
            currentNode=currentNode.next;
        }
    }
    return head;
  }
public static  Node insert(Node head,int data)
{
        Node p=new Node(data);
if(head==null)
head=p;
else if(head.next==null)
head.next=p;
else
{
Node start=head;
while(start.next!=null)
start=start.next;
start.next=p;
}
return head;
    }
public static void display(Node head)
{
Node start=head;
while(start!=null)
{
Console.Write(start.data+" ");
start=start.next;
}
}
    static void Main(String[] args) {
Node head=null;
        int T=Int32.Parse(Console.ReadLine());
        while(T-->0){
            int data=Int32.Parse(Console.ReadLine());
            head=insert(head,data);
        }
      head=removeDuplicates(head);
display(head);
}
}

No comments:

Post a Comment