一、题目
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
说明:不允许修改给定的链表。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。
进阶:
你是否可以不用额外空间解决此题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、分析及代码
1. 双指针
(1)思路
在上一题通过双指针判断链表是否存在环的基础上,可进一步求解环的入口节点。
假设 head 到环入口的距离为 a,环入口到指针相遇处距离为 b,相遇处向前返回到环入口距离为 c (即环长度:b + c)。
由快指针速度为慢指针 2 倍,可得:
a + 2 * b + c = 2 * (a + b)
化简方程,得到:
a = c
因此,只需一个指针从 head、一个指针从相遇处,二者同时以速度1 向前移动,再次相遇时即为入口节点。
(2)代码
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == NULL || head->next == NULL)
return NULL;
if (head->next == head)
return head;
ListNode* node1 = head->next;
ListNode* node2 = head->next->next;
while (node1 != node2) {//判断链表是否存在环,同第141题
if (node2 == NULL || node2->next == NULL)
return NULL;
node2 = node2->next->next;
node1 = node1->next;
}
node2 = head;
while (node1 != node2) {//由前述数学分析,双指针再次指向的同一节点,即为环的入口节点
node1 = node1->next;
node2 = node2->next;
}
return node1;
}
};
(3)结果
执行用时 :12 ms, 在所有 C++ 提交中击败了 90.83% 的用户;
内存消耗 :9.7 MB, 在所有 C++ 提交中击败了 67.29% 的用户。
三、其他
暂无。