Skip to content

Commit db0d430

Browse files
committed
Add week 9 solutions: linked-list-cycle
1 parent 9a8decb commit db0d430

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

linked-list-cycle/gitsunmin.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* https://leetcode.com/problems/linked-list-cycle/
3+
* time complexity : O(n)
4+
* space complexity : O(1)
5+
*/
6+
7+
export class ListNode {
8+
val: number
9+
next: ListNode | null
10+
constructor(val?: number, next?: ListNode | null) {
11+
this.val = (val === undefined ? 0 : val)
12+
this.next = (next === undefined ? null : next)
13+
}
14+
}
15+
16+
function hasCycle(head: ListNode | null): boolean {
17+
if (!head || !head.next) {
18+
return false;
19+
}
20+
21+
let slow: ListNode | null = head;
22+
let fast: ListNode | null = head.next;
23+
24+
while (slow !== fast) {
25+
if (!fast || !fast.next) return false;
26+
slow = slow!.next;
27+
fast = fast.next.next;
28+
}
29+
30+
return true;
31+
};

0 commit comments

Comments
 (0)