-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked-list-cycle-ii.js
42 lines (32 loc) · 1.1 KB
/
linked-list-cycle-ii.js
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
41
42
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var detectCycle = function(head) {
let slow = head;
let fast = head;
while(fast && fast.next && fast.next.next){
slow = slow.next;
/* Move fast pointer twice as fast as slow pointer and if there is a cycle, the fast will eventually meet slow at a node in the cycle but not necessarily the node that starts the cycle */
fast = fast.next.next;
// Once we determine there is a cycle we must find where the cycle starts
if(slow === fast){
// Move slow pointer to the head
slow = head;
// Move both fast and slow pointer one node at a time and they will meet at the node where the cycle starts
while(slow !== fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
};