Created
February 1, 2017 21:59
-
-
Save iturgeon/7b92bee36d9f776c0f748bb882ba17d0 to your computer and use it in GitHub Desktop.
Nth item from the end of a list
This file contains hidden or 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
"use strict"; | |
let nthFromEnd = (startNode, n) => { | |
let rabbit = startNode; | |
let turtle = startNode; | |
while(n--){ | |
rabbit=rabbit.nextNode; | |
} | |
while(rabbit){ | |
rabbit=rabbit.nextNode; | |
turtle=turtle.nextNode | |
} | |
return turtle; | |
} | |
// create 10 node list | |
let nodes = []; | |
for (let i = 0; i < 10; i++){ | |
nodes.push({value:i, nextNode:null}); | |
if(i > 0){ | |
nodes[i-1].nextNode = nodes[i]; | |
} | |
} | |
console.log(nthFromEnd(nodes[0], 3).value); // 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment