Created hasCycle.js

This commit is contained in:
mrwolferinc 2020-12-21 15:54:36 -05:00 committed by GitHub
parent aaad0cb27b
commit 29bd6c8c1c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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
}