Nth to Last Node in List
Written on October 21, 2015
Tweet
Find the nth to last element of a singly linked list. The minimum number of nodes in list is n.
public class Solution {
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: Nth to last node of a singly linked list.
*/
ListNode nthToLast(ListNode head, int n) {
// write your code here
if (head == null) return null;
ListNode fast = head, slow = head;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while(fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
// 3 - 4 - 5 - 6, n = 2
// result should be 5 not 4
}
}