Implement an algorithm to find the \(k\)th to last element of a singly-linked list.
For this solution, I’ll be using the LinkedList
class that I created back in Problem 2.1.
function findKthValueUsingBuffer<T>(input: LinkedList<T>, k: number) {
let current = input.head;
let buffer = new Array(0);
while(current != null) {
if (buffer.length == k) {
buffer.shift();
}
buffer.push(current.data);
current = current.next;
}
return buffer.length == k ? buffer[0] : null;
}
function findKthValueDoubleIterate<T>(input: LinkedList<T>, k: number) {
let current = input.head;
let length = 0;
while(current != null) {
length++;
current = current.next;
}
if (k < length) {
current = input.head;
for (let i = 0; i < length - k; i++) {
current = current?.next || null;
}
}
return k < length ? current?.data || null : null;
}