Last active
August 28, 2018 18:56
-
-
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
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
| 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