2020-05-30 04:23:24 +08:00
|
|
|
struct ListNode *detectCycle(struct ListNode *head)
|
|
|
|
{
|
2019-09-26 23:29:31 +08:00
|
|
|
if (head == NULL || head->next == NULL)
|
|
|
|
return NULL;
|
|
|
|
struct ListNode *slow, *fast;
|
|
|
|
slow = fast = head;
|
2020-05-30 04:23:24 +08:00
|
|
|
while (fast && fast->next)
|
|
|
|
{
|
2019-09-26 23:29:31 +08:00
|
|
|
slow = slow->next;
|
|
|
|
fast = fast->next->next;
|
2020-05-30 04:23:24 +08:00
|
|
|
if (slow == fast)
|
|
|
|
{
|
2019-09-26 23:29:31 +08:00
|
|
|
struct ListNode *entry = head;
|
2020-05-30 04:23:24 +08:00
|
|
|
while (slow != entry)
|
|
|
|
{
|
|
|
|
slow = slow->next;
|
|
|
|
entry = entry->next;
|
2019-09-26 23:29:31 +08:00
|
|
|
}
|
|
|
|
return entry;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return NULL;
|
|
|
|
}
|