/**
* 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 pre = head;
ListNode aft = head;
// 先将pre移动到第k个结点的位置
// 这里直接 while(k!=0) k--
for(int i=0;i<k;i++) {
pre = pre.next;
}
// 然后同时移动两个指针pre和aft,直到pre为空,此时aft指向的就是倒数第k个结点
while (pre != null) {
pre = pre.next;
aft = aft.next;
}
// 返回aft即可
return aft;
}
}
2.2 Kotlin
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
fun getKthFromEnd(head: ListNode, k: Int): ListNode {
// 双指针
var pre: ListNode? = head
var aft = head
// 先将pre移动到第k个结点的位置
for (i in 0 until k) {
pre = pre!!.next
}
// 然后同时移动两个指针pre和aft,直到pre为空,此时aft指向的就是倒数第k个结点
while (pre != null) {
pre = pre!!.next
aft = aft.next
}
// 返回aft即可
return aft
}
}
2.3 复杂度分析
时间复杂度 O(N):N是链表的结点数量。总体来看,pre走了N步,aft走了N-k步。
空间复杂度 O(1):双指针pre和aft使用了常数大小的额外空间。
3. 解法 - 递归
3.1 Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
// 计数器
int cnt = 0;
// 获取倒数第k个结点
public ListNode getKthFromEnd(ListNode head, int k) {
// 递归出口
if (head == null)
return head;
// 先获取后面链表的倒数第k个结点
ListNode node = getKthFromEnd(head.next, k);
// 计数器
cnt++;
// 从最后开始数结点,小于k,返回空
if (cnt < k) {
return null;
} else if (cnt == k){
// 等于k,返回传递的结点
return head;
} else {
// 大于k,找到了,返回即可
return node;
}
}
}