双指针
/**
* 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 i=head;
ListNode j=head;
int t=k-1;
while(t>0){
j=j.next;
--t;
}
while(j.next!=null){
j=j.next;
i=i.next;
}
return i;
}
}
递归
class Solution {
int size;
public ListNode getKthFromEnd(ListNode head, int k) {
if(head==null) return head;
ListNode node=getKthFromEnd(head.next,k);
size++;
if(size<k)
return null;
else if(size==k)
return head;
else
return node;
}
}