LeetCode142:Linked List Cycle II

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

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

前一篇介绍了如何寻找到环,在找到环后可以立马将移动比较快的指针恢复到头指针处,并以后每次向前移动一步。当它们的值相同时即表示是环的入口。
runtime:13ms

/**
 * 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 * slow=head;
        ListNode * fast=head;
        while(slow->next!=NULL&&fast->next!=NULL&&fast->next->next!=NULL)
        {
            slow=slow->next;
            fast=fast->next->next;

            //如果找到了环,将fast指针重新设置为head,并每次移动一步,当它再次和slow相同时就是环的起点
            if(slow==fast)
            {
                fast=head;
                while(slow!=fast)
                {
                    slow=slow->next;
                    fast=fast->next;
                }
                return fast;
            }
        }
        return NULL;
    }
};

你可能感兴趣的:(LeetCode)