Skip to content

Commit a0cc746

Browse files
committed
Feat: 141. Linked List Cycle
1 parent f99d21c commit a0cc746

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

linked-list-cycle/HC-kang.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
/**
11+
* https://leetcode.com/problems/linked-list-cycle
12+
* T.C. O(n)
13+
* S.C. O(n)
14+
*/
15+
function hasCycle(head: ListNode | null): boolean {
16+
const SET = new Set<ListNode>();
17+
while (head) {
18+
if (SET.has(head)) return true;
19+
SET.add(head);
20+
head = head.next
21+
}
22+
return false;
23+
};
24+
25+
/**
26+
* T.C. O(n)
27+
* S.C. O(1)
28+
*/
29+
function hasCycle(head: ListNode | null): boolean {
30+
let fast = head;
31+
let slow = head;
32+
33+
while (fast && fast.next) {
34+
fast = fast.next.next;
35+
slow = slow!.next;
36+
37+
if (fast === slow) {
38+
return true;
39+
}
40+
}
41+
return false;
42+
};

0 commit comments

Comments
 (0)