环形链表 II

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

Note: Do not modify the linked list.

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

题意:找到链表中环开始的位置,如果没有环的话,则返回NULL
思路:首先通过快慢指针,找到相遇的地方,然后将两个指针一个放在head,一个放在相遇的地方,以同样的速度向前走,再相遇的地方就是环开始的地方。
因为快指针走过的距离是慢指针走过的两倍,所以如果能和慢指针相遇,肯定是在环上,(这里可以当作是只在环中走了一圈,这样比较好理解),这样就可以知道直线段的距离,就等于环减去相遇时慢指针在环上走过的那一段距离(妈耶,真应该画图表示,好难表述),然后重新设置指针在head位置和相遇位置,以同样的速度,走相同的时间,就可以到达到他们距离相等的,环开始的位置!虽然是小学数学题,但还是感觉很神奇,,,
/**
 * 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) {
        bool cycle=false;
        ListNode * start=NULL;
        if(head==nullptr || head->next==nullptr) return start;
        ListNode *fast,*slow;
        fast=head;
        slow=head;
        while(fast->next!=nullptr && fast->next->next!=nullptr){
            fast=fast->next->next;
            slow=slow->next;
            if(fast==slow){    //首先找到快慢指针相遇的地方
                cycle=true;
                slow=head;    //将其中一个指针重置为head,另一个从相遇的地方开始,然后以相同的速度前进
                while(fast!=slow){ 
                    fast=fast->next;
                    slow=slow->next;}
                start=fast;  //再次相遇的地方就是环开始的地方
                break;  //记得break,不然就一直不相遇一致循环循环
            }
        }
        if(cycle) return start;
        else return NULL;
    }
};
原文地址:https://www.cnblogs.com/Bipolard/p/9988169.html