/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include <cstdlib> class Solution { public: ListNode *detectCycle(ListNode *head) { // Avoid we have no node here if (head == NULL) return NULL; ListNode *fast = head; ListNode *slow = head; while (fast != NULL && fast->next != NULL) { ListNode *first_choice = fast; ListNode *second_choice = fast->next->next; slow = slow->next; fast = fast->next->next; if (fast == slow) { break; } } // Avoid the entire end and we only have one node here if (fast != slow || fast->next == NULL) return NULL; slow = head; while (slow != fast) { slow = slow->next; fast = fast->next; } return slow; } };