Skip to content

Commit f86cd34

Browse files
author
Kohei Asai
authored
Update soluton: 141 (#118)
1 parent 2c0f859 commit f86cd34

File tree

2 files changed

+17
-28
lines changed

2 files changed

+17
-28
lines changed

Diff for: solutions/linkedListCycle.test.ts

+10-17
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1-
import { createSinglyLinkedListNode } from "../testUtilities/LinkedList";
2-
import { SinglyLinkedListNode } from "../types/LinkedList";
1+
import {
2+
createSinglyLinkedListNode,
3+
getNthNode
4+
} from "../testUtilities/LinkedList";
35
import hasCycle from "./linkedListCycle";
46

57
describe("141. Linked List Cycle", () => {
@@ -10,22 +12,13 @@ describe("141. Linked List Cycle", () => {
1012
]);
1113

1214
for (const [[values, cycleStart], expected] of TEST_CASES) {
13-
it(`returns ${expected} when called with [${values}] (cycle starts from ${cycleStart})`, () => {
14-
const head = createSinglyLinkedListNode(values);
15+
it(`returns ${expected} when called with [${values}] ${
16+
cycleStart === -1 ? "(no cycle)" : `(cycle starts from ${cycleStart})`
17+
}`, () => {
18+
const head = createSinglyLinkedListNode(values)!;
1519

16-
let node = head;
17-
let cycleStartNode: SinglyLinkedListNode<number> | null = null;
18-
19-
for (const i of values.keys()) {
20-
if (i === cycleStart) {
21-
cycleStartNode = node;
22-
}
23-
24-
if (i === values.length - 1) {
25-
node!.next = cycleStartNode;
26-
}
27-
28-
node = node!.next;
20+
if (cycleStart !== -1) {
21+
getNthNode(head, -1).next = getNthNode(head, cycleStart);
2922
}
3023

3124
expect(hasCycle(head)).toBe(expected);

Diff for: solutions/linkedListCycle.ts

+7-11
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,15 @@ import { SinglyLinkedListNode } from "../types/LinkedList";
55
export default function hasCycle<T>(
66
head: SinglyLinkedListNode<T> | null
77
): boolean {
8-
function traverse(
9-
previous: SinglyLinkedListNode<T> | null,
10-
node: SinglyLinkedListNode<T> | null
11-
): boolean {
12-
if (node === null) return false;
13-
if (node === head && previous !== null) return true;
8+
let walker = head;
9+
let runner = head ? head.next : null;
1410

15-
const next = node.next;
11+
while (walker && runner) {
12+
if (walker && walker === runner) return true;
1613

17-
node.next = previous;
18-
19-
return traverse(node, next);
14+
walker = walker.next;
15+
runner = runner.next ? runner.next.next : null;
2016
}
2117

22-
return traverse(null, head);
18+
return false;
2319
}

0 commit comments

Comments
 (0)