mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-10 11:09:43 +08:00
Created hasCycle.js
This commit is contained in:
parent
aaad0cb27b
commit
29bd6c8c1c
27
src/algorithms/linked-list/tortoise-and-hare/hasCycle.js
Normal file
27
src/algorithms/linked-list/tortoise-and-hare/hasCycle.js
Normal 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
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user