方法一:快慢指针法
设环长n,当慢指针刚入环时,快指针已经走了x
因为快指针速度为2,慢指针速度为1,差值为1,快指针为了追上慢指针需要走n-x的路程,
而n-x<=n,所以慢指针第一圈走不完就会和快指针相遇
class Solution
{
public:
ListNode* detectCycle(ListNode* head)
{
if (head == nullptr || head->next == nullptr)
{
return nullptr;
}
ListNode* fast = head;
ListNode* slow = head;
do
{
if (fast == nullptr || fast->next == nullptr)
{
return nullptr;
}
fast = fast->next->next;
slow = slow->next;
} while (fast != slow);
ListNode* ptr = head;
while (ptr != slow)
{
ptr = ptr->next;
slow = slow->next;
}
return ptr;
}
};