Duplicate elements from a singly linked list

Write a Program to remove duplicate elements from a singly linked list

Solution:

using System;

namespace LinkedListOpearation
{
    class Program
    {
        public static void Main()
        {
            var linkedList = new LinkedList();
            linkedList.Add(6);
            linkedList.Add(1);
            linkedList.Add(5);
            linkedList.Add(1);
            linkedList.Add(3);
            linkedList.Add(9);
            Console.WriteLine("Sorted Linked List is:");
            linkedList.Print(linkedList.Head);
            linkedList.RemoveDuplicate();
            Console.WriteLine("After Removing duplicates item from Linked List:");
            linkedList.Print(linkedList.Head);
            Console.ReadLine();
        }   
    }

    
    public class LinkedList
    {
        public Node Head;
        public int Size;
        public void Add(int data)
        {
            var node = new Node(data) {Next = Head};
            Head = node;
            Size++;
        }

        public void RemoveDuplicate()
        {            Node current = Head;

            if (Head == null)
                return;

            while (current != null)
            {
                var temp = current;
                var index = current.Next;

                while (index != null)
                {
                    if (current.Data == index.Data)
                        temp.Next = index.Next;
                    else
                        temp = index;

                    index = index.Next;
                }
                current = current.Next;
            }
        }

        public void Print(Node head)
        {
            while (head != null)
            {
                Console.WriteLine(head.Data);
                head = head.Next;
            }
        }
    }

    public class Node
    {
        public int Data;
        public Node Next;

        public Node(int data)
        {
            Data = data;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *