Skip to content

Commit 60b1537

Browse files
Jeehay28Jeehay28
authored andcommitted
Add linked-list-cycle solution in TS
1 parent e4973c8 commit 60b1537

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

linked-list-cycle/Jeehay28.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class ListNode {
2+
val: number;
3+
next: ListNode | null;
4+
constructor(val?: number, next?: ListNode | null) {
5+
this.val = val === undefined ? 0 : val;
6+
this.next = next === undefined ? null : next;
7+
}
8+
}
9+
10+
// TC: O(n)
11+
// SC: O(1)
12+
function hasCycle(head: ListNode | null): boolean {
13+
14+
let fast: ListNode | null = head;
15+
let slow: ListNode | null = head;
16+
17+
while (fast && fast.next) {
18+
fast = fast.next.next;
19+
20+
if (slow !== null) {
21+
slow = slow.next;
22+
} else {
23+
return false;
24+
}
25+
26+
if (fast === slow) return true;
27+
}
28+
29+
return false;
30+
}
31+
32+
33+
// TC: O(n)
34+
// SC: O(n)
35+
/*
36+
function hasCycle(head: ListNode | null): boolean {
37+
38+
let dummy: ListNode | null = head;
39+
const visited = new Set<ListNode>();
40+
41+
while (dummy) {
42+
if (visited.has(dummy)) return true;
43+
44+
visited.add(dummy);
45+
46+
dummy = dummy.next;
47+
}
48+
49+
return false;
50+
}
51+
*/
52+

0 commit comments

Comments
 (0)