/** * @param {ListNode} head * @return {ListNode} */ const detectCycle = function(head) { if (!head) returnnull; let slow = head; let fast = head; let cycle = false;
while (fast.next && fast.next.next) { slow = slow.next; fast = fast.next.next; if (slow === fast) { cycle = true; break; } }
if (cycle) { slow = head; while (slow !== fast) { slow = slow.next; fast = fast.next; } return slow; }