C# program to delete nth element from headnode
Here's an example of a C# program that deletes the nth element from the head node of a 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 DeleteNthElementFromHead(int n)
{
if (head == null)
{
Console.WriteLine("Linked list is empty.");
return;
}
if (n <= 0)
{
Console.WriteLine("Invalid value of n.");
return;
}
if (n == 1)
{
head = head.Next; // Move head to the next node
return;
}
Node current = head;
int count = 1;
while (current != null && count < n - 1)
{
current = current.Next;
count++;
}
if (current == null || current.Next == null)
{
Console.WriteLine("Invalid value of n.");
return;
}
current.Next = current.Next.Next; // Skip the nth 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 linked list
list.Add(10);
list.Add(20);
list.Add(30);
list.Add(40);
list.Add(50);
// Deleting the 2nd element from the head node
int n = 2;
Console.WriteLine("Linked List before deleting the " + n + "th element from the head:");
list.Traverse();
list.DeleteNthElementFromHead(n);
Console.WriteLine("Linked List after deleting the " + n + "th element from the head:");
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, DeleteNthElementFromHead, and Traverse. The Add method adds a new node to the end of the linked list. The DeleteNthElementFromHead method deletes the nth element from the head node of the 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 to it using the Add method, specify the value of n (in this case, 2) to indicate the position of the element to be deleted from the head, call the DeleteNthElementFromHead method to delete the specified element, 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:
Linked List before deleting the 2nd element from the head:
10 20 30 40 50
Linked List after deleting the 2nd element from the head:
10 30 40 50
This indicates that the 2nd element (20) from the head node was successfully deleted, and the modified elements were printed.