title: How to find nth element from the end of a singly linked list?
body: <p>The following function is trying to find the <code>nth</code> to <strong>last</strong> element of a singly linked list.</p>
  
  <p>For example: </p>
  
  <p>If the elements are <code>8-&gt;10-&gt;5-&gt;7-&gt;2-&gt;1-&gt;5-&gt;4-&gt;10-&gt;10</code> then the result is 
  <code>7th</code> to last node is <code>7</code>.</p>
  
  <p>Can anybody help me on how this code is working or is there a better and simpler approach?</p>
  
  <pre><code>LinkedListNode nthToLast(LinkedListNode head, int n) {
    if (head == null || n &lt; 1) {
      return null;
    }
  
    LinkedListNode p1 = head;
    LinkedListNode p2 = head;
  
    for (int j = 0; j &lt; n - 1; ++j) { // skip n-1 steps ahead
      if (p2 == null) {
        return null; // not found since list size &lt; n
      }
      p2 = p2.next;
    }
  
    while (p2.next != null) {
      p1 = p1.next;
      p2 = p2.next;
    }
  
    return p1;
  }
  </code></pre>