The idea is :

- First, scanning the list using
`slow`

and`fast`

pointers, and using`slowVal`

,`fastVal`

records the steps two pointers have past. If the list has loop, then`fastVal - slowVal`

equals the size of the loop. - Then, let
`slow`

points head, and`fast`

points`loopSize`

ahead. - Let slow and fast points the next until
`slow == fast`

, here we found the begin of the loop.

Here, we scan the list twice, and use constant space.

The code:

```
ListNode *detectCycle(ListNode *head) {
if (head == NULL){
return NULL;
}
ListNode *slow = head, *fast = slow->next;
long long slowVal = 0, fastVal = slowVal + 1;
while (fast != NULL){
if (slow == fast){
break;
}
slow = slow->next;
fast = fast->next;
++slowVal;
++fastVal;
if (fast != NULL){
fast = fast->next;
++fastVal;
}
}
// No loop
if (fast == NULL){
return NULL;
}
long long loopSize = fastVal - slowVal;
slow = fast = head;
while (loopSize){
fast = fast->next;
--loopSize;
}
while (slow != fast){
slow = slow->next;
fast = fast->next;
}
return fast;
}
```

Any comments are welcome.