
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution
{
public:
    ListNode *detectCycle(ListNode *head)
    {
        ListNode *slow = head; //记录慢指针
        ListNode *fast = head; //记录快指针
        ListNode *meet = NULL; //记录相遇点
        while (slow && fast && fast->next)
        { //找出相遇点
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast)
            {
                meet = slow;
                break;
            }
        }
        while (head && meet)
        { //根据相遇的的位置找出环的入口点
            if (meet == head)
            {
                break;
            }
            head = head->next;
            meet = meet->next;
        }
        return meet;
    }
};