File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments