The last k node in the linked list

subject

Enter a linked list and output the k nodes from the bottom of the linked list.

Train of thought

image

Simple idea: loop to the end of linked list to find length, loop twice to find length-k node.

Optimization: set two nodes with a distance of k nodes. when the front node reaches the end point, take the back node.

After the front node arrives at k, the rear node starts.

This topic focuses on the robustness and fault tolerance of the code: consider the case where head is null, k is 0, and k is greater than the length of the linked list.

Code

function FindKthToTail(head, k) {
if (!  head || !  k) return null;
let front = head;
let behind = head;
let index = 1;
while (front.next) {
index++;
front = front.next;
if (index > k) {
behind = behind.next;
}
}
return (k <= index) && behind;
}