File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * function ListNode(val) {
4
+ * this.val = val;
5
+ * this.next = null;
6
+ * }
7
+ */
8
+
9
+ /**
10
+ * @param {ListNode } head
11
+ * @return {boolean }
12
+ */
13
+ var hasCycle = function ( head ) {
14
+ // 순환탐지 기법
15
+ // 1. 플로이드 토끼와 거북이 (포인터2개)
16
+ // 2. 집합을 통한 중복검사
17
+
18
+ ////////풀이///////
19
+
20
+ // 노드 0개 1개면 순환불가
21
+
22
+ if ( ! head || ! head . next ) {
23
+ return false ;
24
+ }
25
+
26
+ // 토끼, 거북이 설정
27
+ let slow = head ;
28
+ let fast = head . next ;
29
+
30
+ while ( slow !== fast ) {
31
+ // 두칸전진시 노드 존재 체크
32
+ if ( ! fast || ! fast . next ) {
33
+ return false ;
34
+ }
35
+
36
+ slow = slow . next ;
37
+ fast = fast . next . next ;
38
+ }
39
+
40
+ return true ;
41
+ } ;
42
+
43
+ // 시간복잡도 O(n) -> 최대 리스트의 노드 수 만큼 while문이 반복되므로
44
+ // 공간복잡도 O(1) -> 토끼, 거북이 포인터 2개만 사용하므로
You can’t perform that action at this time.
0 commit comments