find the first node in a linked list in typescript

To find the first node in a linked list, you need to follow the next property of each node until you find the one that doesn't have a next reference.

Here is the TypeScript code to find the first node in a linked list:

index.ts
class Node<T> {
  data: T;
  next: Node<T> | null;

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

class LinkedList<T> {
  head: Node<T> | null;

  constructor() {
    this.head = null;
  }

  findFirst(): Node<T> | null {
    return this.head;
  }
}
280 chars
22 lines

In the findfirst() method of the LinkedList class, we simply return the head node, which is the first node in the linked list. If the linked list is empty, head will be null.

gistlibby LogSnag