C# program to find nth to last element in singly Linkedlist
Here's a C# program that finds the nth-to-last element in a singly linked list:
using System;
public class Node
{
public int Data;
public Node Next;
public Node(int data)
{
Data = data;
Next = null;
}
}
public class LinkedList
{
private Node head;
public LinkedList()
{
head = null;
}
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 int FindNthToLast(int n)
{
if (head == null || n <= 0)
{
throw new InvalidOperationException("Invalid input");
}
Node first = head;
Node second = head;
// Move the second pointer n positions ahead
for (int i = 0; i < n; i++)
{
if (second == null)
{
throw new InvalidOperationException("List length is less than n");
}
second = second.Next;
}
// Move both pointers until the second pointer reaches the end
while (second != null)
{
first = first.Next;
second = second.Next;
}
return first.Data;
}
}
public class Program
{
public static void Main()
{
LinkedList list = new LinkedList();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
int n = 2; // Find 2nd to last element
int nthToLast = list.FindNthToLast(n);
Console.WriteLine("The {0}nd-to-last element is: {1}", n, nthToLast);
}
}
In this program, the LinkedList class represents a singly linked list with a method Add to add elements to the list. The FindNthToLast method takes an integer n as input and finds the nth-to-last element in the list. It uses two pointers, first and second, to iterate through the list. The second pointer is moved n positions ahead, and then both pointers are moved simultaneously until the second pointer reaches the end of the list. At this point, the first pointer will be pointing to the nth-to-last element.
In the Main method, we create a LinkedList object, add some elements to it, and then call the FindNthToLast method to find the 2nd-to-last element. The result is printed to the console.