Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created May 16, 2021 16:18
Show Gist options
  • Save CarlaTeo/3135419be6b00b1ef5781f78eb8e2941 to your computer and use it in GitHub Desktop.
Save CarlaTeo/3135419be6b00b1ef5781f78eb8e2941 to your computer and use it in GitHub Desktop.
[JS] Check if a linked list has a cycle
// 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