环形链表 II
1. 题目描述
提示
题目链接:https://leetcode.cn/problems/linked-list-cycle-ii/description/
2. 解题思路
核心总结
- 核心算法:
- 确认有环:快慢指针(速度差),相遇则有环。
- 寻找入口:数学推导得知
a = c。让一个指针从头出发,另一个从相遇点出发,同速移动,再次相遇处即为环入口。
💡 易错点
必须利用“速度差”而非“先行探测”。检测环的 while 条件要注意 fast != null && fast.next != null。
3. 代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(slow == fast){
ListNode index1 = fast;
ListNode index2 = head;
while(index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}
|
4. 复杂度分析
- 时间复杂度:$O(n)$
- 空间复杂度:$O(1)$
5. 总结与反思