快慢指针,求解链表环的模板解法。

class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead) {
        if (!pHead || !pHead->next) return nullptr;
        ListNode* fast = pHead->next->next, *slow = pHead->next;
        while (fast && fast != slow) {
            if (!fast->next) return nullptr;
            fast = fast->next->next;
            slow = slow->next;
        }
        if (!fast) return nullptr;
        ListNode* res = pHead;
        while (res != slow) {
            res = res->next;
            slow = slow->next;
        }
        return res;
    }
};