Implement an algorithm to find the nth to last element of a singly linked list.
==========
Analysis:
Similar problem as "Remove Nth Node From End of List" in LeetCode. Idea is to use two pointers, distance between which is n. So, when the right pointer reached the end of the link list, the left pointer is pointing to the nth to last element.
public class Answer {
public static LinkedListNode solution(LinkedListNode head, int n){
if(head == null) return null;
LinkedListNode left = head;
LinkedListNode right = head;
for(int i=0; i<n-1; i++){
if(right.next!=null) right = right.next;
else return null;
}
while(right.next!=null){
left = left.next;
right = right.next;
}
return left;
}
public static void main(String[] args) {
LinkedListNode head = AssortedMethods.randomLinkedList(10, 0, 10);
System.out.println(head.printForward());
int nth = 11;
LinkedListNode n = solution(head, nth);
if (n != null) {
System.out.println(nth + "th to last node is " + n.data);
} else {
System.out.println("null");
}
}
}
Note: Please download crackcode library before running the program.