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

To add a new node to the end of a linked list in TypeScript, you will need to perform the following steps:

  1. Create a new instance of the Node class with the data you want to add.
  2. Traverse the linked list until you reach the end (i.e. where the next value is null).
  3. Set the next value of the last node in the list to the new node you just created.

Here's how you can implement it in TypeScript:

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

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

class LinkedList {
  head: Node | null;

  constructor() {
    this.head = null;
  }

  addNodeToEnd(data: number) {
    const newNode = new Node(data);

    // If the list is empty, set the new node as the head
    if (!this.head) {
      this.head = newNode;
      return;
    }

    let currNode = this.head;

    // Traverse the list until the end is reached
    while (currNode.next) {
      currNode = currNode.next;
    }

    // Set the next value of the last node to the new node
    currNode.next = newNode;
  }
}

// Example usage
const list = new LinkedList();
list.addNodeToEnd(1);
list.addNodeToEnd(2);
list.addNodeToEnd(3);
console.log(list.head); // Node { data: 1, next: Node { data: 2, next: Node { data: 3, next: null } } }
875 chars
45 lines

In this example, we create a LinkedList class with a head property that points to the first node in the list. We also define a Node class that contains a data property and a next property, which points to the next node in the list.

The addNodeToEnd method creates a new node using the provided data and checks whether the list is empty. If it is, it sets the new node as the head. Otherwise, it traverses the list using a while loop until it reaches the end, and then sets the next property of the last node to the new node.

Finally, we create an instance of the LinkedList class and add three nodes to the end of the list. We then log the head property of the list to the console, which outputs the complete list.

gistlibby LogSnag