From 29bd6c8c1cec283535746513edaa5dd512891b9a Mon Sep 17 00:00:00 2001 From: mrwolferinc <66963621+mrwolferinc@users.noreply.github.com> Date: Mon, 21 Dec 2020 15:54:36 -0500 Subject: [PATCH] Created hasCycle.js --- .../linked-list/tortoise-and-hare/hasCycle.js | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/algorithms/linked-list/tortoise-and-hare/hasCycle.js diff --git a/src/algorithms/linked-list/tortoise-and-hare/hasCycle.js b/src/algorithms/linked-list/tortoise-and-hare/hasCycle.js new file mode 100644 index 00000000..12a0aa04 --- /dev/null +++ b/src/algorithms/linked-list/tortoise-and-hare/hasCycle.js @@ -0,0 +1,27 @@ +/** + * @param {object} linkedList - The linked list to check + * @returns {boolean} + */ +export default function hasCycle(linkedList) { + const head = linkedList.head; + + // Check if head and head.next exist + if (!head || !head.next) { + return false; // No cycle was found + } + + let tortoise = head; + let hare = head.next; + + while (hare && hare.next) { + // Check if tortoise and hare are equal to each other + if (tortoise === hare) { + return true; // A cycle was found + } + + tortoise = tortoise.next; + hare = hare.next.next; + } + + return false; // No cycle was found +}