The following function is trying to find the nth to last element of a singly linked list.
For example:
If the elements are
Nobody here noticed that Jonathan's version will throw a NullPinterException if the n is larger that the length of LinkedList. Here is my version:
public Node nth(int n){
if(head == null || n < 1) return null;
Node n1 = head;
Node n2 = head;
for(int i = 1; i < n; i++){
if(n1.next == null) return null;
n1 = n1.next;
}
while (n1.next != null){
n1 = n1.next;
n2 = n2.next;
}
return n2;
}
I just make little change here: when node n1 step forward, instead of checking if n1 is null, I check weather n1.next is null, or else in while loop n1.next will throw a NullPinterException.