经典双指针,快指针先走k步,然后快慢指针一起走到最后。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode L = head;
ListNode R = head;
for (int i = 0; i < k; i++) {
R = R.next;
}
while (R != null) {
R = R.next;
L = L.next;
}
return L;
}
}