Skip to content

Instantly share code, notes, and snippets.

@unilecs
Created October 15, 2017 10:10
Show Gist options
  • Save unilecs/1e0643239837be68fcaf897b5b243921 to your computer and use it in GitHub Desktop.
Save unilecs/1e0643239837be68fcaf897b5b243921 to your computer and use it in GitHub Desktop.
Найти цикл в односвязном списке (@MrMeison)
const node1 = {};
const node2 = {};
const node3 = {};
const node4 = {};
const node5 = {};
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node1;
const findCircle = (node) => {
if (node.next && node.next.next) {
var hare = node.next;
var tortoise = node.next.next;
while (hare !== tortoise) {
hare = hare.next;
if (!hare) return false;
tortoise = tortoise.next;
if (tortoise.next && tortoise.next.next) {
tortoise = tortoise.next.next;
} else {
return false;
}
}
} else {
return false;
}
return true;
}
console.log(findCircle(node1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment