add a node to the beginning of a linked list in typescript

To add a new node at the beginning of a linked list, you need to follow these steps:

  1. Create a new Node object with the desired value
  2. Set the next property of the new node to the current head of the list
  3. Set the head of the list to the new node

Here's the code:

index.ts
class Node<T> {
  value: T;
  next: Node<T> | null;
  
  constructor(value: T) {
    this.value = value;
    this.next = null;
  }
}

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

  constructor() {
    this.head = null;
    this.length = 0;
  }

  addFirst(value: T): void {
    const newNode = new Node(value);
    newNode.next = this.head;
    this.head = newNode;
    this.length++;
  }
}
411 chars
27 lines

In this code, we have a Node class that contains a value property and a next property, which is a reference to the next node in the list. We also have a LinkedList class that contains a head property, which is a reference to the first node in the list, and a length property to keep track of the number of nodes in the list.

The addFirst() method of the LinkedList class creates a new Node object with the given value, sets its next property to the current head of the list, sets the head of the list to the new node, and increments the length of the list.

You can use this method to add a new node to the beginning of the list like this:

index.ts
const list = new LinkedList<number>();
list.addFirst(1);    // list: 1 -> null
list.addFirst(2);    // list: 2 -> 1 -> null
list.addFirst(3);    // list: 3 -> 2 -> 1 -> null
174 chars
5 lines

gistlibby LogSnag