Find the nth to last element of a singly linked list.
The minimum number of nodes in list is n.
Example
Given a List 3->2->1->5->null and n = 2, return node whose value is 1.
解法:创建两个指针,两个指针保持间距为n并同时向后移动直到second指针为空。first指针为倒数第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) {
ListNode first = head;
ListNode second = head;
for(int i = 0; i < n; i++) {
if(second == null) return null;
second = second.next;
}
while(second != null) {
first = first.next;
second = second.next;
}
return first;
}
}