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?

分析:类似于linked list cycle I,用两个pointer,一个每个step往后移一个,另一个每个step往后移两个。当两个指针相交时,快指针走过的路程恰好是慢指针走过的路程的两倍,则我们可以得到:从链表头到环开始点的距离等于从两指针相交点到环开始点的距离(next方向)。那么我们让slow指针继续走,fast指针从head开始往后走(每个step后移一个),当fast和slow重合时即为环开始点。代码如下:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head == NULL || head->next == NULL) return NULL;
        
        ListNode *slow = head, *fast = head;
        //find meeting point
        while(slow->next && fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast) break;
        }
        //no cycle
        if(slow != fast) return NULL;
        //find cycle beginning
        fast = head;
        while(fast != slow){
            fast = fast->next;
            slow = slow->next;
        }
        return fast;
    }
};

 

posted on 2014-11-25 15:05  Ryan-Xing  阅读(110)  评论(0编辑  收藏  举报