/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; */ class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { ListNode* slow = pHead; ListNode* fast = pHead; while(fast!=nullptr) { fast = fast->next; if(fast==nullptr) return nullptr; slow = slow->next; fast = fast->next; if(fast==nullptr) return nullptr; if(fast==slow) break; } fast = pHead; while(fast!=slow) { fast = fast->next; slow = slow->next; } return slow; } };
头结点到入口节点距离与 快慢指针相遇处到入口节点的距离相等
第一次相遇后, 快指针置于phead,和慢指针一样每次只走一步, 再次相遇即是入口节点