题目来源
https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId
解题思路:快慢指针法解决
- 判断
head
和k
的合法性 - 先让
fast
走k-1
步走到指定位置,然后fast
slow
两个指针一起走 fast
指针走到最后一个节点时,slow
指针刚好走到倒数第K个节点
注:需要判断的是fast.next != null
,如果判断fast != null
,slow
最后走到的就是要找的节点的下一个了
图解
这是还没有开始查找之前的示例链表
这是找到倒数第K个节点的示例链表
假设要找的是倒数第2
个节点<——>即下标为3
的节点。
则fast
先走1
步。
实现代码
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public ListNode FindKthToTail(ListNode head, int k) {
//1.判断合法性
if (head == null ||k <= 0) {
return null;
}
ListNode fast = head;
ListNode slow = head;
//2.先让fast走k-1步
while (k - 1 != 0) {
if (fast.next != null) {
fast = fast.next;
k--;
} else {
return null;
}
}
//3.两者一起走
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}