Created
March 4, 2017 12:58
-
-
Save vitkarpov/88a0e7fb0f4c77bb3e7cdaee3869f5ef to your computer and use it in GitHub Desktop.
"Cracking the coding interview". Linked lists, 2.2.1
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
/** | |
* Возвращает k-й элемент с конца списка. | |
* Принимает ссылку на начало спиcка, номер элемента, | |
* а так же специальный объект-хранилище, который нужен | |
* чтобы вернуть ссылку на нужный элемент списка. | |
* | |
* @example | |
* const store = []; | |
* getKthElementToLast(head, 3, store); | |
* const theThirdElement = store.pop(); | |
* | |
* @param {Node} head | |
* @param {Number} k | |
* @param {Array} store | |
* @returns {Number} | |
*/ | |
function getKthElementToLast(head, k, store) { | |
if (head === null) { | |
return 0; | |
} | |
const index = getKthElementToLast(head, k, store) + 1; | |
if (k === index) { | |
store.push(head); | |
} | |
return index; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment