find the last node in a linked list in typescript

Assuming you have implemented a Linked List in TypeScript with a head property that points to the first node, you can iterate through the list until you reach the last node:

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;
  }

  // other methods here...

  getLastNode(): Node<T> | null {
    if (!this.head) {
      return null;
    }

    let currentNode: Node<T> = this.head;

    while (currentNode.next !== null) {
      currentNode = currentNode.next;
    }

    return currentNode;
  }
}
488 chars
34 lines

In the getLastNode() method, we first check if the list is empty (this.head === null), and if so, we return null. Otherwise, we initialize a currentNode variable to the head of the list. We then iterate through the list by following the next pointer of each node (currentNode.next) until we reach the last node (currentNode.next === null). Finally, we return the last node (currentNode).

Note that this implementation assumes that the next property of the last node is null. If you're implementing a circular linked list (where the last node points back to the first node), you'd need to modify this implementation.

gistlibby LogSnag