I’ve written a solution which avoids iterating through the whole list but it returns a null pointer but I can’t figure it out as the line number is not part of the code I have written. Can anyone help?
public static int findNth(linkedList list, int n) {
Node slow = list.headNode;
Node fast = list.headNode;
while (n > 0) {
fast = fast.nextElement;
n--;
}
while (fast.nextElement != null) {
slow = slow.nextElement;
fast = fast.nextElement;
}
return slow.data;
}