题意
如题所示
思路
- 链表中的快慢指针的经典例题
- 先让快的指针走
k
的距离,然后再让快慢指针一起走,他们两个指针之间永远隔着k
的长度, 那么当快指针走到链表末尾的时候我们也就找到了倒数第k
个节点
Java 代码
class Solution {
public int kthToLast(ListNode head, int k) {
if(head == null) return 0;
ListNode fast = head, slow = head;
while(k > 0) {
fast = fast.next;
k--;
}
while(fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow.val;
}
}
Python 代码
class Solution:
def kthToLast(self, head: ListNode, k: int) -> int:
if not head: return head
fast, slow = head, head
while k > 0:
k -= 1
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
return slow.val