find the largest node in a linked list in typescript

To find the largest node in a linked list in TypeScript, we can iterate through the list and keep track of the maximum value we have seen so far. Here's an example implementation:

index.ts
class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val: number, next: ListNode | null = null) {
    this.val = val;
    this.next = next;
  }
}

function findLargest(head: ListNode | null): number | undefined {
  let node = head;
  let largest = head?.val; // initialize largest value to the value of the first node

  while (node) {
    if (node.val > largest) {
      largest = node.val;
    }
    node = node.next;
  }

  return largest;
}
463 chars
23 lines

In this implementation, we define a ListNode class that represents a single node in the linked list. Each ListNode has a val property that stores its value, as well as a next property that points to the next node in the list.

The findLargest function takes the head of the linked list as its input and returns the largest value in the list. It initializes the node variable to the head of the list, sets the largest variable to the value of the first node (if it exists), and then iterates through the list using a while loop. For each node in the list, it checks if its value is greater than the current largest value, and updates largest accordingly. Finally, it returns the largest value.

Note that this implementation assumes that the val property of each node is a numeric value. If the values are of a different type, you will need to modify the comparison logic accordingly.

gistlibby LogSnag