Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save lienista/7494a53405813e3d5a0999be6b6254bc to your computer and use it in GitHub Desktop.

Select an option

Save lienista/7494a53405813e3d5a0999be6b6254bc to your computer and use it in GitHub Desktop.
(Algorithms in Javascript) CTCI 2.2 - Return kth to last - Implement an algorithm to find the kth to last element of a singly linked list
const findKthFromLast = (head, n) => {
if(!head) return head;
if(!head.next && n>0) return [];
let p = head;
let pk = head;
//Move p k elements into the list
for(let i=0; i<n; i++){
p = p.next;
}
//Move both p and pk until p hits end of list
while(p !== null){
p = p.next;
pk = pk.next;
}
return pk;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment