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; }