Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions linked-list-cycle/moonjonghoo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// ## 🔗 문제 링크
// https://leetcode.com/problems/linked-list-cycle/

// ## ✨ 문제 요약
// 연결 리스트에 사이클이 있는지 여부를 판별하는 문제입니다.

// ## ✅ 풀이 방법
// ### 1. HashSet 사용
// - 방문한 노드를 저장하고 중복 방문 시 true
// - 시간복잡도: O(n), 공간복잡도: O(n)

var hasCycle = function (head) {
let visited = new Set();
let current = head;

while (current !== null) {
if (visited.has(current)) {
return true; // 이미 방문한 노드를 다시 방문 => 사이클 존재
}
visited.add(current);
current = current.next;
}

return false; // 끝까지 갔다면 사이클 없음
};

// ### 2. Two Pointer 방식 (Floyd's Algorithm)
// - slow, fast 포인터 이용
// - 만날 경우 → 사이클 존재
// - 끝까지 도달 → 사이클 없음
// - 시간복잡도: O(n), 공간복잡도: O(1)

var hasCycle = function (head) {
let slow = head;
let fast = head;

while (fast !== null && fast.next !== null) {
slow = slow.next; // 한 칸 이동
fast = fast.next.next; // 두 칸 이동

if (slow === fast) {
return true; // 만났다면 사이클 존재!
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 Floyd's Algorithm을 해당 문제를 통해 처음 접했는데요, 찾아보다가 이 알고리즘을 linked list의 cycle 존재 여부를 판별할 때 뿐만 아니라 cycle의 길이를 계산하거나 cycle의 시작점을 찾을 때에도 사용할 수 있다는 것도 알게되었습니다!

다양한 사용 방법과 원리에 대해 정리가 잘 되어있는 블로그 글이 있어 함께 공유드립니다~! (링크: https://yuminlee2.medium.com/floyds-cycle-detection-algorithm-b27ed50c607f)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

정리 감사합니다. 바빠서 문제를 다풀지못했네요ㅠㅠ 한주간 고생하셧습니다.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이번 주 고생 정말 많으셨습니다~! 🍀

}
}

return false; // 끝까지 갔다면 사이클 없음
};