https://leetcode.com/problems/linked-list-cycle-ii/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The node where the cycle begins.
* if there is no cycle, return null
*/
ListNode *detectCycle(ListNode *head) {
if (!head) return head;
ListNode *slow = head, *fast = head;
bool isCycle = false;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (fast == slow) {
isCycle = true;
break;
}
}
if (!isCycle) return NULL;
ListNode *u = head;
while (u != slow) {
u = u->next;
slow = slow->next;
}
return u;
}
};