1. 程式人生 > >Leetcode: Linked List Cycle II

Leetcode: Linked List Cycle II

/**
 * 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* fastHead=head;
        ListNode* slowHead=head;
        // get the first meeting point
        while(true){
            slowHead=slowHead->next;
            fastHead=fastHead->next;
            if(fastHead==NULL) return NULL;
            fastHead=fastHead->next;
            if(fastHead==NULL) return NULL;
            if(fastHead==slowHead) break;
        }
        // get the length of the cycle
        int cnt=1;
        slowHead=slowHead->next;
        while(slowHead!=fastHead){
            slowHead=slowHead->next;
            cnt++;
        }
        // start from the head and make the fastHead ahead of slowHead by cnt nodes
        fastHead=slowHead=head;
        while(cnt!=0){
            fastHead=fastHead->next;
            cnt--;
        }
        while(fastHead!=slowHead){
            fastHead=fastHead->next;
            slowHead=slowHead->next;
        }
        return fastHead;
    }
};