1
1
/**
2
- * A LinkedList based solution for Detecting a start node of the Cycle in a list.
3
- * https://en.wikipedia.org/wiki/Cycle_detection
2
+ * A LinkedList based solution for finding the starting node of the cycle in a list.
3
+ * @returns the node where cycle begins in the linked list. If there is no cycle present, returns null.
4
+ * @see https://en.wikipedia.org/wiki/Cycle_detection
5
+ * @see https://leetcode.com/problems/linked-list-cycle-ii/
4
6
*/
5
7
6
8
function detectCycleNode ( head ) {
7
- /*
8
- Problem Statement:
9
- Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
10
- Link for the Problem: https://leetcode.com/problems/linked-list-cycle-ii/
11
- */
12
-
9
+
13
10
let length = 0
14
11
let fast = head
15
12
let slow = head
@@ -25,14 +22,12 @@ function detectCycleNode(head) {
25
22
}
26
23
27
24
if ( length === 0 ) {
28
- // If length = 0 , return null
25
+ // If there is no cycle , return null.
29
26
return null
30
27
}
31
28
32
- //Point the nodes at head
33
- fast = head
34
- slow = head
35
- // Move slow pointer ahead by 'length' of cycle times
29
+ fast = slow = head
30
+ // Move slow pointer ahead by 'length' (integer) of cycle times
36
31
while ( length > 0 ) {
37
32
slow = slow . next
38
33
length --
@@ -44,7 +39,7 @@ function detectCycleNode(head) {
44
39
slow = slow . next
45
40
}
46
41
47
- // return the meeting node
42
+ // return the meeting node (fast/slow)
48
43
return slow
49
44
}
50
45
@@ -74,4 +69,4 @@ function lengthCycle(head) {
74
69
return 0
75
70
}
76
71
77
- export { detectCycleNode }
72
+ export { detectCycleNode }
0 commit comments