From 6d0c7f48a4f8c6a3ae04f65a090a96bcd2d23af0 Mon Sep 17 00:00:00 2001 From: youngduck Date: Tue, 16 Sep 2025 09:18:06 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20cycle=EB=AC=B8=EC=A0=9C=ED=92=80?= =?UTF-8?q?=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- linked-list-cycle/youngduck.js | 44 ++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 linked-list-cycle/youngduck.js diff --git a/linked-list-cycle/youngduck.js b/linked-list-cycle/youngduck.js new file mode 100644 index 000000000..d18b916ad --- /dev/null +++ b/linked-list-cycle/youngduck.js @@ -0,0 +1,44 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function (head) { + // 순환탐지 기법 + // 1. 플로이드 토끼와 거북이 (포인터2개) + // 2. 집합을 통한 중복검사 + + ////////풀이/////// + + // 노드 0개 1개면 순환불가 + + if (!head || !head.next) { + return false; + } + + // 토끼, 거북이 설정 + let slow = head; + let fast = head.next; + + while (slow !== fast) { + // 두칸전진시 노드 존재 체크 + if (!fast || !fast.next) { + return false; + } + + slow = slow.next; + fast = fast.next.next; + } + + return true; +}; + +// 시간복잡도 O(n) -> 최대 리스트의 노드 수 만큼 while문이 반복되므로 +// 공간복잡도 O(1) -> 토끼, 거북이 포인터 2개만 사용하므로