Nth to Last Node

Given a linked-list, return the nth to last node on the list.

Node<T> getNthToLast<T>(Node<T> head, int n)
{
    if (head == null)
        return null;
 
    Node<T> curr = head;
    Node<T> nBehind = head;
 
    for (int i = 0; i <= n; i++)
    {
        if (curr == null)
            return null;
        curr = curr.next;
    }
 
    while (curr != null)
    {
        curr = curr.next;
        nBehind = nBehind.next;
    }
 
    return nBehind;
}
Comments