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

To find the range of all nodes in a linked list, we need to iterate through the list and keep track of the minimum and maximum values of the nodes. Here's an implementation of this algorithm in TypeScript:

index.ts
class Node {
  value: number;
  next: Node | null;

  constructor(value: number, next: Node | null = null) {
    this.value = value;
    this.next = next;
  }
}

function getRange(head: Node | null): [number, number] | null {
  if (head === null) {
    return null;
  }

  let min = head.value;
  let max = head.value;

  let current = head.next;
  while (current !== null) {
    min = Math.min(min, current.value);
    max = Math.max(max, current.value);
    current = current.next;
  }

  return [min, max];
}
512 chars
28 lines

We first check if the linked list is empty, and return null if it is. We then initialize min and max to be the value of the first node. We iterate through the rest of the list, updating min and max as necessary. Finally, we return [min, max].

gistlibby LogSnag