Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head)
{
if(NULL == head)
return false;
struct ListNode *slow = head;
struct ListNode *fast = head;
struct ListNode *entry = head;
while(slow && fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
{
while(slow != entry)
{
slow = slow->next;
entry = entry->next;
}
return entry;
}
}
return NULL;
}
力扣中国上有一篇非常棒的解题思路:142. Linked List Cycle II