Friday, September 19, 2014

[Leetcode] 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?
Analysis:


分析:以上图为例,假设从开始点1cycle开始点4的距离为h,假设fastslow在点7碰到而且从47的距离为a,整个cycle的长度为c;假设fast走了n圈,slow走了m圈,fast走的是slow的两倍那么我们就有
H + n*c + a = 2 ( h + m*c + a)
==>
(n-m)c = h + a

也就是说,如果两个指针slow7开始走,phead开始走,那么最终他们还是会碰到7这点。因为slowp的速度是一样的,所以,他们的456这几点肯定是重合的,那么第一个重合的点就是cycle开始的点。

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

No comments:

Post a Comment