find the kth largest node in a linked list in javascript

To find the kth largest node in a linked list, we can follow the below steps:

  1. Traverse the linked list to find its length.
  2. Calculate the index of the kth largest node, which is length - k.
  3. Traverse the linked list again and return the node at the index calculated in the previous step.

Here's the implementation of the above algorithm in JavaScript:

index.tsx
function findKthLargestNode(head, k) {
  // get the length of the linked list
  let length = 0;
  let current = head;
  while (current !== null) {
    length++;
    current = current.next;
  }

  // calculate the index of the kth largest node
  let index = length - k;

  // traverse the linked list to find the kth largest node
  current = head;
  for (let i = 0; i < index; i++) {
    current = current.next;
  }
  return current;
}
435 chars
20 lines

This function takes the head of the linked list and the value of k as input and returns the kth largest node in the linked list.

gistlibby LogSnag