LeetCode 142. 环形链表 II

142. 环形链表 II

解题思路

快慢指针,如果有环,快慢指针一定会相遇。
相遇后,同时移动头节点和慢指针,每次移动一步,直到相遇,相遇的节点就是环的入口节点。

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {
while(head != slow) {
head = head.next;
slow = slow.next;
}
return slow;
}
}
return null;
}
}

LeetCode 142. 环形链表 II
https://sowink.cn/2026/02/08/LeetCode-142-环形链表-II/
作者
Xurx
发布于
2026年2月8日
许可协议