递归版,因为既要传一个node也要传数字回来,所以只能写个wrapper。
class Solution {
class IntWrapper {
public int value = 0;
}
public ListNode kthLast(ListNode head, int k, IntWrapper i) {
if(head == null) return null;
ListNode node = kthLast(head.next, k, i);
i.value = i.value + 1;
if(k == i.value) {
node = head;
}
return node;
}
}
非递归版:
class Solution {
public ListNode kthLast(ListNode head, int k) {
ListNode l1 = head, l2 = head;
for(int i = 0; i < k; i++) {
if(l2 == null) return null;
l2 = l2.next;
}
while(l2 != null) {
l1 = l1.next;
l2 = l2.next;
}
return l1;
}
}