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

To add a node to the beginning of a linked list in JavaScript, we need to follow these steps:

  1. Create a new node with the required data.
  2. Set the next pointer of the new node to the current head of the linked list.
  3. Set the head of the linked list to the new node.

Below is the code snippet to add a node to the beginning of a linked list in JavaScript:

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

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

  addAtBeginning(data) {
    const newNode = new Node(data);
    newNode.next = this.head;
    this.head = newNode;
  }
}

// Example usage
const linkedList = new LinkedList();
linkedList.addAtBeginning(1);
linkedList.addAtBeginning(2);

console.log(linkedList.head.data); // Output: 2
console.log(linkedList.head.next.data); // Output: 1
489 chars
27 lines

In the code snippet above, we create a Node class with two properties data and next. We also create a LinkedList class that has a single property head that initially points to null.

We create a method addAtBeginning that accepts data as a parameter, creates a new node with the data and sets its next pointer to the current head of the linked list. Finally, we set the head of the linked list to the new node.

We then create an instance of the LinkedList class and add two nodes to it using the addAtBeginning method. We then log the data of the head node and the node next to it to the console to validate that the implementation works as expected.

gistlibby LogSnag