两个指针,快的先走k个,然后一起走到头,看slow位置。画画就会了。
/**
* 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 slow = head;
ListNode fast = head;
for(int i = 0; i < k; i++){
fast = fast.next;
}
if(fast == null){
return head;
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
return slow.next;
}
}