-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
40 lines (38 loc) · 922 Bytes
/
Solution.cs
File metadata and controls
40 lines (38 loc) · 922 Bytes
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
36
37
38
39
40
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution
{
public ListNode DetectCycle(ListNode head)
{
ListNode slow = head;
ListNode fast = head;
while (slow != null && fast != null)
{
slow = slow.next;
fast = fast.next?.next;
if (slow == fast) break;
}
// slow = X + k
// fast = 2X + 2k
// fast = 2X + 2k = X + k + nC
// X + k = nC => k = nC - X
// slow + X = X + k + X = X + nC - X + X = X + nC
if (slow == null || fast == null) return null;
ListNode ret = head;
while (ret != slow)
{
ret = ret.next;
slow = slow.next;
}
return ret;
}
}