Skip to content

Commit a0e1c7e

Browse files
committed
feat: Upload linked-list-cycle(typescript)
1 parent 79481bf commit a0e1c7e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

โ€Žlinked-list-cycle/mike2ox.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Source: https://leetcode.com/problems/linked-list-cycle/
3+
* ํ’€์ด๋ฐฉ๋ฒ•: Set์„ ์ด์šฉํ•˜์—ฌ ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๋ฅผ ์ €์žฅํ•˜๊ณ  ์ˆœํšŒํ•˜๋ฉด์„œ ์ค‘๋ณต๋œ ๋…ธ๋“œ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธ
4+
*
5+
* ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
6+
* ๊ณต๊ฐ„๋ณต์žก๋„: O(n)
7+
*/
8+
9+
// class ListNode {
10+
// val: number;
11+
// next: ListNode | null;
12+
// constructor(val?: number, next?: ListNode | null) {
13+
// this.val = val === undefined ? 0 : val;
14+
// this.next = next === undefined ? null : next;
15+
// }
16+
// }
17+
18+
function hasCycle(head: ListNode | null): boolean {
19+
if (head === null) return false;
20+
21+
// ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๋“ค์„ ์ €์žฅํ•  Set
22+
const addr = new Set<ListNode>();
23+
24+
// ์ฒซ ๋…ธ๋“œ ์ถ”๊ฐ€
25+
addr.add(head);
26+
head = head.next;
27+
28+
// ๋ฆฌ์ŠคํŠธ ์ˆœํšŒ
29+
while (head !== null) {
30+
// ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ์ธ ๊ฒฝ์šฐ cycle ์กด์žฌ
31+
if (addr.has(head)) return true;
32+
33+
// ์ƒˆ๋กœ์šด ๋…ธ๋“œ ์ถ”๊ฐ€
34+
addr.add(head);
35+
head = head.next;
36+
}
37+
38+
return false;
39+
}

0 commit comments

Comments
ย (0)