5
5
* @see https://leetcode.com/problems/linked-list-cycle-ii/
6
6
*/
7
7
8
- function detectCycleNode ( head ) {
8
+ function findCycleStart ( head ) {
9
9
let length = 0
10
10
let fast = head
11
11
let slow = head
@@ -14,8 +14,7 @@ function detectCycleNode(head) {
14
14
fast = fast . next . next
15
15
slow = slow . next
16
16
if ( fast === slow ) {
17
- // Calculate length of the cycle
18
- length = lengthCycle ( slow )
17
+ length = cycleLength ( slow )
19
18
break
20
19
}
21
20
}
@@ -25,47 +24,34 @@ function detectCycleNode(head) {
25
24
return null
26
25
}
27
26
28
- fast = slow = head
29
- // Move slow pointer ahead by 'length' (integer) of cycle times
27
+ let ahead = head
28
+ let behind = head
29
+ // Move slow pointer ahead 'length' of cycle times
30
30
while ( length > 0 ) {
31
- slow = slow . next
31
+ ahead = ahead . next
32
32
length --
33
33
}
34
34
35
35
// Now move both pointers until they meet - this will be the start of cycle
36
- while ( fast !== slow ) {
37
- fast = fast . next
38
- slow = slow . next
36
+ while ( ahead !== behind ) {
37
+ ahead = ahead . next
38
+ behind = behind . next
39
39
}
40
40
41
- // return the meeting node (fast/slow)
42
- return slow
41
+ // return the meeting node
42
+ return ahead
43
43
}
44
44
45
- function lengthCycle ( head ) {
46
- let fast = head
47
- let slow = head
48
-
49
- while ( fast !== null && fast . next !== null ) {
50
- fast = fast . next . next
51
- slow = slow . next
52
-
53
- // when fast and slow meet inside the cycle, calculate the length
54
- if ( fast === slow ) {
55
- let temp = slow
56
- let length = 0
57
-
58
- // Traverse until we reach initial cycle pointer again
59
- do {
60
- temp = temp . next
61
- length ++
62
- } while ( temp !== slow )
63
-
64
- return length
65
- }
66
- }
67
-
68
- return 0
45
+ // head is a node on a cycle
46
+ function cycleLength ( head ) {
47
+ // How long until we visit head again?
48
+ let cur = head
49
+ let len = 0
50
+ do {
51
+ cur = cur . next
52
+ len ++
53
+ } while ( cur != head )
54
+ return len
69
55
}
70
56
71
- export { detectCycleNode }
57
+ export { findCycleStart }
0 commit comments