mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
25 lines
578 B
JavaScript
25 lines
578 B
JavaScript
/**
|
|
* A LinkedList based solution for Detecting a Cycle in a list.
|
|
* https://en.wikipedia.org/wiki/Cycle_detection
|
|
*/
|
|
|
|
function detectCycle (head) {
|
|
/*
|
|
Problem Statement:
|
|
Given head, the head of a linked list, determine if the linked list has a cycle in it.
|
|
Link for the Problem: https://leetcode.com/problems/linked-list-cycle/
|
|
*/
|
|
if (!head) { return false }
|
|
|
|
let slow = head
|
|
let fast = head.next
|
|
while (fast && fast.next) {
|
|
if (fast === slow) { return true }
|
|
fast = fast.next.next
|
|
slow = slow.next
|
|
}
|
|
return false
|
|
}
|
|
|
|
export { detectCycle }
|