C# program to remove duplicates from a sorted Linkedlist
Here's an example of a C# program that removes duplicates from a sorted singly linked list:
using System;
class Node
{
public int Data;
public Node Next;
public Node(int data)
{
Data = data;
Next = null;
}
}
class LinkedList
{
private Node head;
public void Add(int data)
{
Node newNode = new Node(data);
if (head == null)
{
head = newNode;
}
else
{
Node current = head;
while (current.Next != null)
{
current = current.Next;
}
current.Next = newNode;
}
}
public void RemoveDuplicates()
{
if (head == null || head.Next == null)
{
return; // No duplicates to remove
}
Node current = head;
while (current != null && current.Next != null)
{
if (current.Data == current.Next.Data)
{
current.Next = current.Next.Next; // Skip the duplicate node
}
else
{
current = current.Next; // Move to the next node
}
}
}
public void Traverse()
{
Node current = head;
while (current != null)
{
Console.Write(current.Data + " ");
current = current.Next;
}
Console.WriteLine();
}
}
class Program
{
static void Main(string[] args)
{
LinkedList list = new LinkedList();
// Adding elements to the sorted linked list
list.Add(10);
list.Add(20);
list.Add(20);
list.Add(30);
list.Add(30);
list.Add(40);
list.Add(50);
// Removing duplicates from the sorted linked list
list.RemoveDuplicates();
// Traversing the modified linked list
Console.WriteLine("Sorted Linked List after removing duplicates:");
list.Traverse();
}
}
This program creates a singly linked list class (LinkedList) that contains a private Node class. The Node class represents each node in the linked list and holds the data and a reference to the next node.
The LinkedList class provides three methods: Add, RemoveDuplicates, and Traverse. The Add method adds a new node to the end of the linked list. The RemoveDuplicates method removes duplicates from the sorted linked list. The Traverse method traverses the linked list and prints the data of each node.
In the Main method, we create an instance of LinkedList, add some elements (including duplicates) to it using the Add method, call the RemoveDuplicates method to remove duplicates, and then call the Traverse method to print the elements in the modified linked list.
When you run this program, it will output the following:
Sorted Linked List after removing duplicates:
10 20 30 40 50
This indicates that the duplicates were successfully removed from the sorted linked list, and the modified elements were printed.