linked-list-cycle-ii——链表,找出开始循环节点

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——链表,找出开始循环节点
设:链表头是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相遇!也就是环的第一个节点。
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *detectCycle(ListNode *head) {
12         if(head==NULL)
13             return NULL;
14         ListNode *fast=head,*slow=head;
15         ListNode *res=NULL;
16         while(fast!=NULL&&fast->next!=NULL){
17             fast=fast->next->next;
18             slow=slow->next;
19             if(fast==slow){
20                 res=fast;
21                 break;
22             }
23         }
24         if(res==NULL)
25             return res;
26         
27         fast=head;
28         while(fast!=res){
29             fast=fast->next;
30             res=res->next;
31         }
32         return res;
33     }
34 };