[230822] Leetcode - 141. Linked List Cycle
Leetcode 1문제
- 141. Linked List Cycle
- 사이클이 있는지 없는지 확인하는 문제
- 토끼와 거북이로 풀면 된다.
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function (head) {
let curNode = head;
let fastNode = head;
while (true) {
if (!curNode?.next) break;
if (!fastNode?.next || !fastNode?.next?.next) break;
fastNode = fastNode.next.next;
curNode = curNode.next;
if (fastNode === curNode) return true;
}
return false;
};
Leave a comment