2019-11-02 12:07:41 +08:00
|
|
|
|
# 22. 链表中倒数第 K 个结点
|
|
|
|
|
|
2021-03-23 02:48:19 +08:00
|
|
|
|
[牛客网](https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9?tpId=13&tqId=11167&tab=answerKey&from=cyc_github)
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
## 解题思路
|
|
|
|
|
|
|
|
|
|
设链表的长度为 N。设置两个指针 P1 和 P2,先让 P1 移动 K 个节点,则还有 N - K 个节点可以移动。此时让 P1 和 P2 同时移动,可以知道当 P1 移动到链表结尾时,P2 移动到第 N - K 个节点处,该位置就是倒数第 K 个节点。
|
|
|
|
|
|
2019-12-06 10:11:23 +08:00
|
|
|
|
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/6b504f1f-bf76-4aab-a146-a9c7a58c2029.png" width="500"/> </div><br>
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public ListNode FindKthToTail(ListNode head, int k) {
|
|
|
|
|
if (head == null)
|
|
|
|
|
return null;
|
|
|
|
|
ListNode P1 = head;
|
|
|
|
|
while (P1 != null && k-- > 0)
|
|
|
|
|
P1 = P1.next;
|
|
|
|
|
if (k > 0)
|
|
|
|
|
return null;
|
|
|
|
|
ListNode P2 = head;
|
|
|
|
|
while (P1 != null) {
|
|
|
|
|
P1 = P1.next;
|
|
|
|
|
P2 = P2.next;
|
|
|
|
|
}
|
|
|
|
|
return P2;
|
|
|
|
|
}
|
|
|
|
|
```
|