Skip to content

Instantly share code, notes, and snippets.

@jfarmer
Last active September 8, 2023 12:07
Show Gist options
  • Save jfarmer/eb89178b5f730aa996bbc79b2fcf9d3c to your computer and use it in GitHub Desktop.
Save jfarmer/eb89178b5f730aa996bbc79b2fcf9d3c to your computer and use it in GitHub Desktop.
Given a linked list and a non-negative integer k, add k to every kth element from the end of the linked list
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment