/*
快慢指针查找链表是否有环
fast 每次走两步 low 走一步 
当两个指针相遇时,fast 比 low 多走一倍
然后 fast 从头开始走
a 为链表头到链表环结点的距离, b 为 环入口到相遇点距离  c 为 相遇点到环入口的距离
则 low  走了 a+b  fast 走了  a + (b+c)*k(圈数) + b  = (a + b) * 2
a+b = (b+c)*k
即:链表头到环入口的距离 = 相遇点到 环入口的距离 + (k-1)圈的长度
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead)
    {
        ListNode *fast = pHead;
        ListNode *slow = pHead;

        while (fast && fast->next) {
            fast = fast->next->next;  
            slow = slow->next;
            if (fast == slow) break;
        }

        if (!fast || !fast->next) return nullptr;
        fast = pHead; // 
        while (fast != slow) {
            fast = fast->next; 
            slow = slow->next;
        }
        return fast;
    }
};