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

To find the mode of all nodes in a linked list, we need to iterate through every node in the linked list and count the occurrences of each unique value. Once we have counted all the occurrences, we can find the value(s) that occur the most frequently.

Here's the TypeScript code to find the mode of a linked list:

index.ts
interface Node<T> {
  value: T;
  next: Node<T> | null;
}

function findMode<T>(head: Node<T>): T[] {
  const counts = new Map<T, number>();
  let maxCount = 0;
  let modeValues: T[] = [];

  // Iterate through each node in the linked list
  let node = head;
  while (node !== null) {
    const value = node.value;

    // Increment the count of the value
    const count = (counts.get(value) ?? 0) + 1;
    counts.set(value, count);

    // Update the max count and mode values
    if (count > maxCount) {
      maxCount = count;
      modeValues = [value];
    } else if (count === maxCount) {
      modeValues.push(value);
    }

    node = node.next;
  }

  return modeValues;
}
683 chars
33 lines

This function takes the head of the linked list as input and returns an array of mode values. It uses a Map to keep track of the counts for each unique value and updates maxCount and modeValues as it iterates through the linked list. Finally, it returns the mode values.

gistlibby LogSnag