find the smallest node in a linked list in javascript

To find the smallest node in a linked list, we can use recursion to traverse through the nodes and compare them with each other. Here's a JavaScript function that implements this approach:

index.tsx
function findSmallestNode(head) {
  // base case: empty list
  if (!head) {
    return null;
  }

  // base case: single node list
  if (!head.next) {
    return head;
  }

  // recursive case: find smallest node in the rest of the list
  const smallestNode = findSmallestNode(head.next);

  // compare current node with smallest node from rest of list
  return head.data < smallestNode.data ? head : smallestNode;
}
417 chars
18 lines

This function takes the head node of the linked list as input and returns the smallest node in the list. It checks if the list is empty, contains a single node or has multiple nodes. If it has multiple nodes, it recursively calls itself to find the smallest node in the rest of the list, then compares the current node with the smallest node found so far and returns the smaller of the two nodes.

gistlibby LogSnag