## Find nth to last element of a singly linked list

Implement an algorithm to find the nth to last element of a singly linked list.

My initial thoughts:
Finding the nth to last element = Finding the (size – n + 1) first element. So we first get the size of the list and then traverse from the beginning.

My initial codes:

```	public static LLNode<Integer> nthLastElement(LLNode<Integer> head, int n) {
int size = 0;
while (current != null) {
size++;
current = current.getNext();
}
int pos = size - n + 1;
int i = 1;
if (pos == 1)
else
do {
i++;
current = current.getNext();
} while (current != null && i != pos);
return current;
}

Works fine for most inputs. Time complexity O(n) and space complexity O(1).
Failed for empty list. Add one sentence after highlighted line:
if(head == null || n < 0 || n > size) return null;

Solution:
The solution gives another insight of this question:

Create two pointers, p1 and p2, that point to the beginning of the node.
Increment p2 by n-1 positions, to make it point to the nth node from the beginning (to make the distance of n between p1 and p2).
Check for p2->next == null if yes return value of p1, otherwise increment p1 and p2. If next of p2 is null it means p1 points to the nth node from the last as the distance between the two is n.
Repeat Step 3.

public static LLNode<Integer> nthToLast(LLNode<Integer> head, int n) {
if (head == null || n < 1) {
return null;
}
for (int j = 0; j < n - 1; ++j) { // skip n-1 steps ahead
if (p2 == null) {
}
p2 = p2.getNext();
}
while (p2.getNext() != null) {
p1 = p1.getNext();
p2 = p2.getNext();
}
return p1;
}

__ATA.cmd.push(function() {
__ATA.initVideoSlot('atatags-370373-5b2deb072f0f5', {
sectionId: '370373',
});
});

__ATA.cmd.push(function() {
__ATA.initSlot('atatags-26942-5b2deb072f12f',  {
collapseEmpty: 'before',
sectionId: '26942',
width: 300,
height: 250
});
});

__ATA.cmd.push(function() {
__ATA.initSlot('atatags-114160-5b2deb072f132',  {
collapseEmpty: 'before',
sectionId: '114160',
width: 300,
height: 250
});
});