

判断出来有环之后,根据等量关系可以找到入环点。
cpp
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if ( !head || !head->next ) return nullptr;
ListNode *slow = head, *fast = head, *ptr = head;
while ( fast && fast->next ) {
slow = slow->next, fast = fast->next->next;
if ( slow == fast ) {
for ( ; ptr != slow; ptr = ptr->next, slow = slow->next );
return ptr;
}
}
return nullptr;
}
};