0142.cpp (565B)
1 class Solution { 2 public: 3 ListNode *detectCycle(ListNode *head) { 4 if (!head) return nullptr; 5 6 ListNode *slow, *fast; 7 fast = slow = head; 8 while (fast->next && fast->next->next) { 9 fast = fast->next->next; 10 slow = slow->next; 11 if (fast == slow) { 12 fast = head; 13 while (fast != slow) { 14 fast = fast->next; 15 slow = slow->next; 16 } 17 return slow; 18 } 19 } 20 return nullptr; 21 } 22 };