题目描述
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中,要求使用O(1)的空间复杂度
链接:https://leetcode-cn.com/problems/linked-list-cycle-ii
解题思路

a+(n+1)b+nc=2(a+b)⟹a=c+(n−1)(b+c)
即有a = (n-1)(b+c) + c,那么再另一个指针,最终会在环口相遇
/*** 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 (slow != NULL && fast != NULL) {slow = slow->next;if (fast->next == NULL)return NULL;fast = fast->next->next;if (slow == fast)break;}if (slow==NULL || fast==NULL)return NULL;ListNode* pivot=head;while (pivot != slow) {pivot = pivot->next;slow = slow->next;}return pivot;}};
