
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
ListNode *slow = head, *fast = head;
while (fast != nullptr)
{
slow = slow->next;
if (fast->next == nullptr)
{
return nullptr;
}
fast = fast->next->next;
if (fast == slow)
{
ListNode *ptr = head;
while (ptr != slow)
{
ptr = ptr->next;
slow = slow->next;
}
return ptr;
}
}
return nullptr;
}
};
1749

被折叠的 条评论
为什么被折叠?



