题目:Given a linked list, return the node where the cycle begins. If there is no cycle, return null
解析:根据141题的思路,声明一个慢指针和一个快指针,若存在环,则肯定相遇。借用一篇博客里的图,讲解一下如何求环开始节点。
如下图所示:快慢指针相遇时,快指针走的距离为:f=x+y+z+y;慢指针走的距离为s=x+y;而f=2s;据此我们可以得到x=z。所以在相遇后,我们可以让慢指针指向头结点,当两个指针再次相遇的位置,即为环开始的节点。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast,*slow;
fast=head;
slow=head;
while(fast!=NULL&&fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
break;
}
if(fast==NULL||fast->next==NULL)
return NULL;
slow=head;
while(slow!=fast)
{
slow=slow->next;
fast=fast->next;
}
return slow;
}
};