find the median of all nodes in a linked list in javascript

To find the median of all nodes in a linked list, we can use the following algorithm:

  1. Traverse the linked list and find its length.
  2. Traverse the linked list again, this time stopping at the middle node (or the one before it, if the length is even).
  3. If the length is even, calculate the median as the average of the middle two nodes. Otherwise, the median is the value of the middle node.

Here's the code:

index.tsx
function findMedian(head) {
  // step 1: find the length of the linked list
  let length = 0;
  let current = head;
  while (current !== null) {
    length++;
    current = current.next;
  }
  
  // step 2: traverse the linked list to find the middle node
  let middle = Math.floor(length / 2);
  current = head;
  for (let i = 0; i < middle; i++) {
    current = current.next;
  }
  
  // step 3: calculate the median
  if (length % 2 === 0) {
    return (current.value + current.next.value) / 2;
  } else {
    return current.value;
  }
}
541 chars
24 lines

This function takes the head of a linked list as its parameter and returns the median of all its nodes. It first finds the length of the linked list by traversing it using a while loop. It then finds the middle node by traversing the linked list again and stopping at the middle node using a for loop. Finally, it calculates the median by checking if the length is even or odd and returning the appropriate value.

gistlibby LogSnag