The following function is trying to find the nth
to last element of a singly linked list.
For example:
If the elements are
Here is C# version of finding nth child from Linklist.
public Node GetNthLast(Node head, int n)
{
Node current, nth;
current = nth = head;
int counter = 0;
while (current.next != null)
{
counter++;
if (counter % n == 0)
{
for (var i = 0; i < n - 1; i++)
{
nth = nth.next;
}
}
current = current.next;
}
var remainingCounts = counter % n;
for (var i = 0; i < remainingCounts; i++)
{
nth = nth.next;
}
return nth;
}