Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up:
Can you solve it without using extra space?

快慢指针找重合判断是否循环、而后fast从头开始+1,slow继续前进直到重合

思路解析:

首先我们看一张图;

linked-list-cycle-ii——链表,找出开始循环节点-LMLPHP
设:链表头是X,环的第一个节点是Y,slow和fast第一次的交点是Z。各段的长度分别是a,b,c,如图所示。环的长度是L。第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。因为fast的速度是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c。让两个指针分别从X和Z开始走,每次走一步,那么正好会在Y相遇!也就是环的第一个节点。
 /**
* 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) {
if(head==NULL)
return NULL;
ListNode *fast=head,*slow=head;
ListNode *res=NULL;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow){
res=fast;
break;
}
}
if(res==NULL)
return res; fast=head;
while(fast!=res){
fast=fast->next;
res=res->next;
}
return res;
}
};
05-11 13:06