1.题目

2.解法1(递归法)
public class Solution {
private int index = 0;
public ListNode FindKthToTail(ListNode head,int k) {
// 利用递归
if (head == null) return null;
ListNode tmp = FindKthToTail(head.next, k);
// 使用本次循环的点
if (++index == k) return head;
return tmp;
}
}
== 时间复杂度为O(n),空间复杂度为O(n) —这个是用于递归栈的开销==
解法2(双指针法)
public class Solution {
public ListNode FindKthToTail(ListNode head, int k) {
if (head == null || k <= 0) return null;
// 让两个指针之间的距离保持k
ListNode pre = head;
ListNode move = head;
for (int i = 1; i < k; i++) {
// 如果直接出现结果,那就返回
// 指针要对等
if (move.next != null) {
move = move.next;
} else {
return null;
}
}
while (move.next != null) {
pre = pre.next;
move = move.next;
}
return pre;
}
}
== 时间复杂度为O(n),空间复杂度为O(1)==
462

被折叠的 条评论
为什么被折叠?



