Created
October 15, 2017 10:10
-
-
Save unilecs/1e0643239837be68fcaf897b5b243921 to your computer and use it in GitHub Desktop.
Найти цикл в односвязном списке (@MrMeison)
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
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