一、题目
二、代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
环前 环中 环剩余长度
A B C
第一次相遇
low 走了 A+B
fast 走了 A + B +n(B+C)
fast 是 low 两倍速度
2A + 2B= A + B + n*(B+C)
A+ B = nB + nC
A= (n-1)B +nC
A=(n-1)(B+C) + C //目的是凑整圈 从相遇节点出发 相遇一定是在入口处(因为剩下的长度是相等的了)
*/
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
ListNode * fast=head;
ListNode * slow=head;
if(head==nullptr) return nullptr;
while(fast->next!=nullptr)
{
fast=fast->next;
if(fast->next!=nullptr)
{
fast=fast->next;
slow=slow->next;
if(fast==slow) //如果相遇
{
ListNode * from_head=head;
ListNode * from_meeting=fast;
while(from_head!=from_meeting)
{
from_head=from_head->next;
from_meeting=from_meeting->next;
}
return from_head;
}
}
}
//因为必定是要在while里面返回正确解
return nullptr;
}
};