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)