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

To find the mode of all nodes in a linked list, we can iterate through the linked list and store the values of the nodes in an array. Then, we can use a counting algorithm to find the mode of the array. Here's the code:

index.tsx
function findMode(head) {
  let current = head;
  const values = [];
  
  // Store values of all nodes in an array
  while (current) {
    values.push(current.value);
    current = current.next;
  }
  
  // Count the frequency of each value
  const count = {};
  let maxCount = 0;
  let mode = null;
  
  for (let i = 0; i < values.length; i++) {
    const val = values[i];
    count[val] = (count[val] || 0) + 1;
    
    if (count[val] > maxCount) {
      maxCount = count[val];
      mode = val;
    }
  }
  
  return mode;
}
529 chars
28 lines

Here, head is the head node of the linked list. We first iterate through the linked list and store the values of all nodes in the values array. Then, we use a object count to count the frequency of each value in the values array. Finally, we iterate through the count object to find the value with the highest frequency, which is the mode of the array. We then return the mode.

Note that this implementation assumes that there is only one mode in the array. If there are multiple modes, this implementation will return the first mode that it finds.

gistlibby LogSnag