remove a node from the end of a linked list in typescript

Here's how to remove a node from the end of a linked list in TypeScript:

index.ts
class Node {
  public value: number;
  public next: Node | null;

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

class LinkedList {
  public head: Node | null;
  public tail: Node | null;

  constructor() {
    this.head = null;
    this.tail = null;
  }

  public removeLast() {
    if (!this.head) {
      return; // List is empty, nothing to remove
    }
    if (!this.head.next) {
      this.head = null; // List has only one node, remove it
      return;
    }

    let secondToLast = this.head;
    let last = this.head.next;
    while (last.next !== null) {
      secondToLast = last;
      last = last.next;
    }
    secondToLast.next = null;
    this.tail = secondToLast;
  }
}
725 chars
39 lines

Explanation:

We start by checking if the list is empty or has only one node. If that's the case, we just update the head and/or tail pointer to null (if removing the last node).

If the list has two or more nodes, we iterate over the nodes until we reach the second to last node. Once we get there, we update its next pointer to null, effectively removing the last node from the list. We also update the tail pointer to point to the second to last node.

gistlibby LogSnag