Created
May 16, 2021 16:18
-
-
Save CarlaTeo/3135419be6b00b1ef5781f78eb8e2941 to your computer and use it in GitHub Desktop.
[JS] Check if a linked list has a cycle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using strategy of slower and faster pointers | |
class Node { | |
constructor(data) { | |
this.data = data; | |
this.next = null; | |
} | |
} | |
function hasCycle(head) { | |
if(!head) return false; | |
let slower = head; | |
let faster = head.next; | |
while(faster) { | |
if(slower === faster) return true; | |
if(!faster.next) return false; | |
slower = slower.next; | |
faster = faster.next.next; | |
} | |
return false; | |
} | |
// ------------------------------------------- Test ---------------------------------------------------// | |
// null | |
console.log(hasCycle(null)); // false | |
// head | |
const head = new Node(); | |
console.log(hasCycle(head)); // false | |
// head -> head | |
head.next = head; | |
console.log(hasCycle(head)); // true | |
// head -> node1 | |
const node1 = new Node(); | |
head.next = node1; | |
console.log(hasCycle(head)); // false | |
// head -> node1 -> node2 | |
const node2 = new Node(); | |
node1.next = node2; | |
console.log(hasCycle(head)); // false | |
// head -> node1 -> node2 -> node1 | |
node2.next = node1; | |
console.log(hasCycle(head)); // true | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment