Skip to content

Commit ddf256f

Browse files
committed
Simplify code, renames for clarity
1 parent 1d3d600 commit ddf256f

File tree

1 file changed

+22
-36
lines changed

1 file changed

+22
-36
lines changed

Data-Structures/Linked-List/CycleDetectionII.js

Lines changed: 22 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
* @see https://leetcode.com/problems/linked-list-cycle-ii/
66
*/
77

8-
function detectCycleNode(head) {
8+
function findCycleStart(head) {
99
let length = 0
1010
let fast = head
1111
let slow = head
@@ -14,8 +14,7 @@ function detectCycleNode(head) {
1414
fast = fast.next.next
1515
slow = slow.next
1616
if (fast === slow) {
17-
// Calculate length of the cycle
18-
length = lengthCycle(slow)
17+
length = cycleLength(slow)
1918
break
2019
}
2120
}
@@ -25,47 +24,34 @@ function detectCycleNode(head) {
2524
return null
2625
}
2726

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
3030
while (length > 0) {
31-
slow = slow.next
31+
ahead = ahead.next
3232
length--
3333
}
3434

3535
// 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
3939
}
4040

41-
// return the meeting node (fast/slow)
42-
return slow
41+
// return the meeting node
42+
return ahead
4343
}
4444

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
6955
}
7056

71-
export { detectCycleNode }
57+
export { findCycleStart }

0 commit comments

Comments
 (0)