Currently tackling the challenge known as Finding the K-th last element of a singly linked list:
Your task is to create a function that, given the head of a singly linked list and an index (0 based) counted from the end of the list, returns the element at that index.
The function should return a falsy value for invalid input values, such as an out-of-range index.
For instance, in the list
66 -> 42 -> 13 -> 666
, invoking getKthLastElement() with an index of 2 should yield the Node object corresponding to 42.
I'm puzzled because instead of a number, I keep getting undefined in my return
. When testing this code on Codepen, everything seems fine and the result is a number. What could be causing the discrepancy?
function getKthLastElement(head, k) {
let arr = [];
while(head){
arr.push(head.data);
head = head.next;
}
if(k == 0) k = 1;
let result = arr.splice(-k, 1);
return +result;
}