Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
借用博客http://www.cnblogs.com/hiddenfox/p/3408931.html的图
设环的距离为L = (b+c),无环的距离为a,
假设在时间t相遇,慢指针行驶距离为x,则 1 x t = x,即t=x
则快指针行驶的距离为2t = 2x,
则慢指针环上停留点为(x-a)%L,快指针停留点为 (2x-a)%L,由于在t时刻相遇,故(x-a)%L = (2x-a)%L,
根据同余定理 x%L = 0,
当快指针相遇后减慢速度为1,快指针从z继续行走a长度停下,则行走的路程为2x+a,在环上的位置为(2x+a-a)%L = 2x%L=2(x%L) = 0,即回到环的起始点,故知道环的起始点
ListNode* hasCycle(ListNode* head){ if(head == NULL || head->next == NULL) return false; ListNode* first = head, *second = head; while(second!=NULL && second->next!=NULL){ first = first->next; second = second->next->next; if(first == second) return first; } return NULL; } ListNode *detectCycle(ListNode *head){ ListNode* cycleNode = hasCycle(head); if(cycleNode != NULL){ ListNode* startNode = head; while(startNode!=cycleNode){ cycleNode = cycleNode->next; startNode = startNode->next; } } return cycleNode; }