find the smallest node in a linked list in typescript

One way to find the smallest node in a linked list is to traverse the list and keep track of the minimum element seen so far. Here's an implementation in TypeScript:

index.ts
class Node<T> {
  value: T;
  next: Node<T>;

  constructor(value: T) {
    this.value = value;
    this.next = null;
  }
}

function findSmallestNode<T>(head: Node<T>): Node<T> {
  let smallestNode = head;
  let currNode = head;

  while (currNode !== null) {
    if (currNode.value < smallestNode.value) {
      smallestNode = currNode;
    }
    currNode = currNode.next;
  }

  return smallestNode;
}
405 chars
24 lines

The findSmallestNode function takes the head of the linked list as input and returns the smallest node in the list. It initializes the smallestNode variable to the head of the list and then iterates over the list, updating smallestNode whenever it encounters a node with a smaller value. Finally, it returns smallestNode.

Note that this implementation assumes that the values in the linked list are comparable via the < operator. If the values are more complex objects, you may need to provide a custom comparison function to the findSmallestNode function.

gistlibby LogSnag