Find loop in linked list
by Yaroslav Samardak
JavaScript
class Link {
constructor(next) {
this.next = next;
}
}
const l5 = new Link();
const l4 = new Link(l5);
const l3 = new Link(l4);
const l2 = new Link(l3);
const l1 = new Link(l2);
l5.next = l2;
let current1 = l1;
let current2 = l2;
let i = 0;
function check() {
if (!current2) {
console.log('Finity!');
return true;
}
if (current1 === current2) {
console.log('Infinity!');
return true;
}
return false;
}
while (++i < 1000) {
if (check()) break;
current1 = current1.next;
current2 = current2.next;
if (current2) current2 = current2.next;
}
if (i === 1000) {
console.log('Game over')
} else {
console.log('You win!', i);
}