Leetcode: linked-list-cycle-ii
Given a linked list, return the node where the cycle begins. If there isno cycle, returnnull.
Follow up:
Can you solve it without using extra space?
思路:
假设S速度为v,L速度为2v,它们在上图跑步,有个环,环的长度为k,环之外有条长度为a的跑道。S和L从I点开始跑,由于L跑得块,因此过一段事件它们在C点相遇了,此时S跑的路程为a+b,L跑的路程为a+k+b,也就是L比S多跑了一圈的路程相遇了,相遇的时间相同。那么可以得到公式
由这个式子知道,假如在相遇之后,S返回起点I按v的速度跑步,同时L按V的速度在相遇点C跑步,由于速度相同,它们一定会在入环点V相遇,而后两人陪伴着一起跑步到达C点为a+b,L跑的路程为a+k+b,也就是L比S多跑了一圈的路程相遇了,相遇的时间相同。那么可以得到公式。
ListNode *detectCycle(ListNode *head) {
if(!head || !head->next)
return NULL;
ListNode* ptr = head;
ListNode* ctr = head;
while(ctr && ctr->next )
{
ptr = ptr->next;
ctr = ctr->next->next;
if(ptr == ctr)
break;
}
if(!ctr || !ctr->next)
return NULL;
ptr = head;
while(ptr != ctr)
{
ptr = ptr->next;
ctr = ctr->next;
}
return ctr;
}