Skip to content

Commit 1cc1f8b

Browse files
authored
Update implementation to match question (careercup#59)
The original implementation did not answer the question in the book. closes careercup#58
1 parent 685adc5 commit 1cc1f8b

File tree

1 file changed

+22
-17
lines changed

1 file changed

+22
-17
lines changed

chapter02/2.8 - Loop Detection/loopDetection.js

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,27 @@
11
var LinkedList = require('./../util/LinkedList');
22

33
var loopDetection = (head) => {
4-
var hare = head;
5-
var tortoise = head;
6-
while (hare !== null) {
7-
tortoise = tortoise.next;
8-
hare = hare.next;
9-
if (hare === tortoise && hare !== head.next) {
10-
return true;
11-
}
12-
if (hare !== null) {
13-
hare = hare.next;
14-
if (hare === tortoise) {
15-
return true;
16-
}
17-
}
4+
// The null checking code will handle lists with no loops.
5+
if (!head || !head.next) return null
6+
7+
var hare = head
8+
var tortoise = head
9+
10+
do {
11+
hare = hare.next
12+
tortoise = tortoise.next
13+
if (!hare || !hare.next) return null
14+
hare = hare.next
15+
} while (hare !== tortoise)
16+
17+
tortoise = head
18+
19+
while (hare !== tortoise) {
20+
hare = hare.next
21+
tortoise = tortoise.next
1822
}
19-
return false;
23+
24+
return hare
2025
};
2126

2227
/* TEST */
@@ -36,7 +41,7 @@ d.next = e;
3641
e.next = f;
3742
f.next = c;
3843

39-
console.log(loopDetection(a), true);
44+
console.log(loopDetection(a) === c, true);
4045

4146
var A = new LinkedList();
4247
var B = new LinkedList();
@@ -51,4 +56,4 @@ C.next = D;
5156
D.next = E;
5257
E.next = F;
5358

54-
console.log(loopDetection(A), false);
59+
console.log(loopDetection(A) === null, false);

0 commit comments

Comments
 (0)