Skip to content

Commit fb9bcbd

Browse files
committed
Linked List Cycle Solution
1 parent 6a9b8f1 commit fb9bcbd

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

linked-list-cycle/clara-shin.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// 주어진 연결 리스트에서 사이클이 있는지 판단하는 문제
2+
// 사이클: 연결 리스트의 어떤 노드가, 이전에 방문했던 노드를 다시 가리키는 경우
3+
4+
// 문제접근:
5+
// 1) hashset : 직관적
6+
// 2) two pointers : 플로이드의 사이클 탐지 알고리즘(토끼와 거북이 알고리즘)
7+
8+
/**
9+
* Definition for singly-linked list.
10+
* function ListNode(val) {
11+
* this.val = val;
12+
* this.next = null;
13+
* }
14+
*/
15+
16+
/** two pointers로 접근
17+
* 시간복잡도: O(n)
18+
* 공간복잡도: O(1) - ✅ follow-up 고려
19+
* @param {ListNode} head
20+
* @return {boolean}
21+
*/
22+
var hasCycle = function (head) {
23+
if (!head || !head.next) return false;
24+
25+
let slow = head; // 거북이: 한 칸씩
26+
let fast = head; // 토끼: 두 칸씩
27+
28+
while (fast && fast.next) {
29+
slow = slow.next; // 한 칸 이동
30+
fast = fast.next.next; // 두 칸 이동
31+
32+
// 두 포인터가 만나면 사이클 존재한다
33+
if (slow === fast) {
34+
return true;
35+
}
36+
}
37+
38+
return false;
39+
};
40+
41+
/**
42+
* hashset으로 접근
43+
* 시간복잡도: O(n)
44+
* 공간복잡도: O(n)
45+
*/
46+
var hasCycle2 = function (head) {
47+
if (!head) return false;
48+
49+
const visited = new Set();
50+
let current = head;
51+
52+
while (current) {
53+
// 이미 방문한 노드라면 사이클 존재한다
54+
if (visited.has(current)) {
55+
return true;
56+
}
57+
58+
// 현재 노드를 방문 기록에 추가
59+
visited.add(current);
60+
current = current.next;
61+
}
62+
63+
return false;
64+
};

0 commit comments

Comments
 (0)