See code below in file: add-k-from-end-recursive.js
Output:
See code below in file: add-k-from-end-recursive.js
Output:
| class Node { | |
| constructor(value, next = null) { | |
| this.value = value; | |
| this.next = next; | |
| } | |
| toString() { | |
| if (this.next === null) { | |
| return `${this.value}`; | |
| } | |
| return `${this.value} -> ${this.next}`; | |
| } | |
| } | |
| function isEmpty(node) { | |
| return node === null; | |
| } | |
| function addKFromEndWithLength(head, k) { | |
| if (isEmpty(head)) { | |
| return [head, 0]; | |
| } | |
| let first = head.value; | |
| let rest = head.next; | |
| let [restPlusK, length] = addKFromEndWithLength(rest, k); | |
| if ((length + 1) % k === 0) { | |
| return [new Node(first + k, restPlusK), length + 1] | |
| } else { | |
| return [new Node(first, restPlusK), length + 1] | |
| } | |
| } | |
| function addKFromEnd(head, k) { | |
| let [result, length] = addKFromEndWithLength(head, k); | |
| return result; | |
| } | |
| let list = [10,20,30,40,50,60,70,80,90].reduceRight((next, val) => new Node(val, next), null); | |
| console.log('k | result'); | |
| console.log('--+----------') | |
| for (let k = 0; k <= 9; k++) { | |
| let result = addKFromEnd(list, k); | |
| console.log("%d | %s", k, result); | |
| } |