Skip to content

Instantly share code, notes, and snippets.

@iturgeon
Created February 1, 2017 21:59
Show Gist options
  • Save iturgeon/7b92bee36d9f776c0f748bb882ba17d0 to your computer and use it in GitHub Desktop.
Save iturgeon/7b92bee36d9f776c0f748bb882ba17d0 to your computer and use it in GitHub Desktop.
Nth item from the end of a list
"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