create a linked list in typescript

To create a linked list in TypeScript, we first need to define a class for our nodes. Each node in a linked list contains a value and a pointer to the next node in the list.

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

  constructor(value: any, next: Node | null = null) {
    this.value = value;
    this.next = next;
  }
}
169 chars
10 lines

Next, we can define our LinkedList class which will contain methods for adding, removing, and searching for nodes in the linked list.

index.ts
class LinkedList {
  private head: Node | null;

  constructor() {
    this.head = null;
  }

  // Add a new node to the end of the linked list
  public add(value: any) {
    const newNode = new Node(value);
    if (!this.head) {
      this.head = newNode;
    } else {
      let current = this.head;
      while (current.next) {
        current = current.next;
      }
      current.next = newNode;
    }
  }

  // Remove the first node with the given value
  public remove(value: any) {
    if (!this.head) {
      return;
    }
    if (this.head.value === value) {
      this.head = this.head.next;
      return;
    }
    let current = this.head;
    while (current.next && current.next.value !== value) {
      current = current.next;
    }
    if (current.next && current.next.value === value) {
      current.next = current.next.next;
    }
  }

  // Search for the first node with the given value
  public search(value: any): Node | null {
    let current = this.head;
    while (current) {
      if (current.value === value) {
        return current;
      }
      current = current.next;
    }
    return null;
  }

  // Print the linked list values
  public print() {
    let current = this.head;
    while (current) {
      console.log(current.value);
      current = current.next;
    }
  }
}
1306 chars
61 lines

With these classes, we can create a new linked list and add, remove, and search for nodes:

index.ts
const list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.print(); // prints "1", "2", "3"
list.remove(2);
list.print(); // prints "1", "3"
const node = list.search(3);
console.log(node?.value); // prints "3"
226 chars
10 lines

gistlibby LogSnag