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

To remove a node from the beginning of a singly linked list in TypeScript, follow these steps:

  1. Check if the linked list is empty. If it is empty, return null as there are no nodes to remove.
  2. If the linked list is not empty, set the head of the linked list to its next node. This will effectively remove the first node.
  3. Return the removed node to the caller.

Here is the TypeScript code that implements this logic:

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

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

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

  constructor() {
    this.head = null;
  }

  public removeFromBeginning(): Node<T> | null {
    if (this.head === null) {
      return null;
    }

    const removedNode: Node<T> = this.head;
    this.head = this.head.next;

    return removedNode;
  }
}
454 chars
29 lines

To use this code, first create a linked list instance, then call its removeFromBeginning method to remove the first node, like this:

index.ts
const linkedList: LinkedList<string> = new LinkedList<string>();
// ... add nodes to the linked list ...

const removedNode: Node<string> | null = linkedList.removeFromBeginning();
if (removedNode !== null) {
  // Do something with the removed node...
}
254 chars
8 lines

gistlibby LogSnag