Problem
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.
Note
依然是一道找倒数第n个结点的链表题,用双指针做。fast先走n,然后fast和slow一起走,直到fast为null,slow的位置就是倒数第n个位置。
Solution
public class Solution {
ListNode nthToLast(ListNode head, int n) {
ListNode fast = head, slow = head;
int i = n;
while (i-- > 0) fast = fast.next;
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}