File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class ListNode {
2+ val : number ;
3+ next : ListNode | null ;
4+ constructor ( val ?: number , next ?: ListNode | null ) {
5+ this . val = val === undefined ? 0 : val ;
6+ this . next = next === undefined ? null : next ;
7+ }
8+ }
9+
10+ /**
11+ * @param head - linked list node
12+ * @returns - 순환되는 리스트인지?
13+ * @description
14+ * - 풀이 1. - 단순 순회 및 조회로 판단, 결국 visit에 다시 돌아온다면 순환
15+ * - 풀이 2. - 1칸, 2칸 포인터를 나눠 결국 순환이라면 돌고 돌아 만나는 과정을 통한 메모리 O(1)의 풀이
16+ */
17+
18+ // function hasCycle(head: ListNode | null): boolean {
19+ // const visit = new Set();
20+ // let current = head;
21+
22+ // while (current) {
23+ // if (visit.has(current)) {
24+ // return true;
25+ // }
26+
27+ // visit.add(current);
28+ // current = current.next;
29+ // }
30+
31+ // return false;
32+ // }
33+
34+ function hasCycle ( head : ListNode | null ) : boolean {
35+ if ( ! head || ! head . next ) {
36+ return false ;
37+ }
38+
39+ let slow : ListNode | null = head ;
40+ let fast : ListNode | null = 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+ return false ;
51+ }
52+
53+
You can’t perform that action at this time.
0 commit comments