142. 环形链表 II

给定一个链表的头节点  head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。

不允许修改 链表。

示例 1:

**输入:**head = [3,2,0,-4], pos = 1
**输出:**返回索引为 1 的链表节点
**解释:**链表中有一个环,其尾部连接到第二个节点。

示例 2:

**输入:**head = [1,2], pos = 0
**输出:**返回索引为 0 的链表节点
**解释:**链表中有一个环,其尾部连接到第一个节点。

示例 3:

**输入:**head = [1], pos = -1
**输出:**返回 null
**解释:**链表中没有环。

提示:


定义fastslow指针,fast指针每次前进两个结点,slow指针每次前进一个结点。
设$x$为头节点到环入口距离,$y$为从环入口到fastslow相遇节点的距离,$z$为相遇节点到环入口距离。

则相遇时,fast走过$n(y+z)+x$个结单,slow走过$x+y$个结点,其中$n$为fast在环内绕的圈数。

fast走过的结点数是slow的两倍:$2(x+y) = n(y+z) + x$
整理得:$x = (n-1)(y+z) +z$

当$n=1$,$x=z$,此时可以在相遇节点与头节点分别设置指针index1index2。它们每次走一个结点,相遇处即为环入口。

$n>1$时同理。
![[Pasted image 20250405130912.png]]


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
62
63
/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 */

class Solution {

public:

    ListNode *detectCycle(ListNode *head) {

        ListNode *fast=head;

        ListNode *slow=head;

        while(fast != nullptr && fast ->next != nullptr)

        {

            fast = fast->next->next;

            slow = slow->next;

            if(fast == slow)

            {

                ListNode *index1 = head;

                ListNode *index2 = fast;

                while(index1 != index2)

                {

                    index1 = index1 ->next;

                    index2 = index2 ->next;

                }

                return index1;

            }

        }

        return nullptr;

    }

};

上次更新 2025-04-05