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

To add a node to the end of a linked list in JavaScript, you can follow these steps:

  1. Create a new node object with your desired value.
  2. Check if the linked list is empty. If it is, set the head of the linked list to the new node.
  3. If the linked list is not empty, traverse the linked list until you reach the last node.
  4. Set the last node's next pointer to the new node.
  5. The new node's next pointer should be set to null, indicating that it is now the tail of the linked list.

Here is the implementation in JavaScript:

index.tsx
class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
  }

  addNode(value) {
    const newNode = new Node(value);

    if (!this.head) {
      // if linked list is empty, set head to new node
      this.head = newNode;
    } else {
      let current = this.head;

      while (current.next) {
        // traverse linked list until you reach the last node
        current = current.next;
      }

      current.next = newNode; // set last node's next pointer to new node
    }

    newNode.next = null; // set new node's next pointer to null (tail)
  }
}
649 chars
33 lines

Now you can create a new linked list object and add nodes to the end of it:

index.tsx
const linkedList = new LinkedList();
linkedList.addNode(1);
linkedList.addNode(2);
linkedList.addNode(3);
console.log(linkedList); // output: LinkedList { head: Node { value: 1, next: Node { value: 2, next: Node { value: 3, next: null } } } }
243 chars
6 lines

gistlibby LogSnag