[leetcode_142] Linked List Cycle II

Determine whether a linked list has a cycle, and return the node where the cycle begins. If there is no cycle, return NULL.
Detecting whether a linked list has a cycle without allocating extra space was mentioned in a previous blog post:
http://blog.sina.com.cn/s/blog_672f71fc0101odsf.html
How to find the entry node of the cycle?
If we can calculate the number of nodes k in the cycle, then using the approach of removing the nth node from the end:
http://blog.sina.com.cn/s/blog_672f71fc0101pfx6.html
This problem can be solved.
Here is the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head == NULL)
            return NULL;
        ListNode * p1 = head;
        ListNode * p2 = head->next;
        if(p2 == NULL)
            return NULL;
        p2 = head->next;
        while(true)
        {
            if(p2 == NULL)
            {
                return NULL;
            }
            else
                if(p1 == p2)
                {
                    break;
                }
                else
                {
                    p1 = p1->next;
                    p2 = p2->next;
                    if(p2 == NULL)return NULL;
                    p2 = p2->next;
                }
        }
        int k = 1;
        p1 = p1->next;
        p2 = p2->next->next;
        while(p1 != p2)
        {
            p1 = p1->next;
            p2 = p2->next->next;
            k++;
        }
        p1 = head;
        p2 = head;
        for(int i = 0;i < k;i++)
        {
            p2 = p2->next;
        }
        while(p1 != p2)
        {
            p1 = p1->next;
            p2 = p2->next;
        }
        return p1;
    }
};