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
44 changes: 44 additions & 0 deletions linked-list-cycle/youngduck.js
Original file line number Diff line number Diff line change
@@ -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;
Copy link
Contributor

@sonjh1217 sonjh1217 Sep 20, 2025

Choose a reason for hiding this comment

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

달리기시합이다 보니까(??)ㅋㅋ 토끼와 거북이가 출발선을 갖게 하구
각기 한칸, 두칸씩 전진하면서 토끼가 거북이를 따라 잡으면 -> 싸이클이 있는 것
토끼가 끝에 도달하면 -> 싸이클이 없는 것
으로 짜는 방안도 좋은 것 같습니다.

let slow = head;
let fast = head;

while (fast && fast.next) {   
  slow = slow.next;           
  fast = fast.next.next;     
  if (slow === fast) return true;
}
return false; 


while (slow !== fast) {
// 두칸전진시 노드 존재 체크
if (!fast || !fast.next) {
return false;
}

slow = slow.next;
fast = fast.next.next;
}

return true;
};

// 시간복잡도 O(n) -> 최대 리스트의 노드 수 만큼 while문이 반복되므로
// 공간복잡도 O(1) -> 토끼, 거북이 포인터 2개만 사용하므로