Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

Detailed mathmetic explanation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/

public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head, slow = head;
boolean isCycle = false;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
isCycle = true;
break;
}
}

// # of fast = 2 * # of slow = # of meeting node + circle = # of slow + circle
// => # of slow = circle
// distance from head to the circle entry = distance from meeting node to circle entry
if (!isCycle) return null;
while (head != slow) {
head = head.next;
slow = slow.next;
}
return head;
}
}