File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 문제 설명
3+ * - 링크드리스트 내에 cycle이 존재하는지 확인하는 문제
4+ *
5+ * 아이디어
6+ * - 링크드리스트를 끝까지 순회하면서 방문한 노드를 저장하고, 방문한 노드가 존재하면 cycle이 존재하는 것으로 판단
7+ * - 시간복잡도: O(n), 공간복잡도 O(n)
8+ *
9+ */
10+
11+ class ListNode {
12+ val : number ;
13+ next : ListNode | null ;
14+ constructor ( val ?: number , next ?: ListNode | null ) {
15+ this . val = val === undefined ? 0 : val ;
16+ this . next = next === undefined ? null : next ;
17+ }
18+ }
19+
20+ function hasCycle ( head : ListNode | null ) : boolean {
21+ const visited = new Set < ListNode > ( ) ;
22+
23+ while ( head ) {
24+ if ( visited . has ( head ) ) {
25+ return true ;
26+ } else {
27+ visited . add ( head ) ;
28+ head = head . next ;
29+ }
30+ }
31+ return false ;
32+ }
33+
34+ /**
35+ * 공간복잡도 O(1) 로도 풀 수 있음.
36+ */
37+
38+ // function hasCycle(head: ListNode | null): boolean {
39+ // let slow = head;
40+ // let fast = head;
41+
42+ // while (fast && fast.next) {
43+ // slow = slow!.next;
44+ // fast = fast.next.next!;
45+
46+ // if (slow === fast) {
47+ // return true;
48+ // }
49+ // }
50+
51+ // return false;
52+ // }
You can’t perform that action at this time.
0 commit comments