how to implement a linked list in javascript

To implement a Linked List in JavaScript, we need to create two classes:

  1. Node class — A class to represent each element in the Linked List.
  2. LinkedList class — A class to represent the Linked List itself.

Here's an example of how to implement a singly Linked List in JavaScript:

index.tsx
// Node class to represent each element in the Linked List
class Node {
  constructor(data) {
    this.data = data;
    this.next = null; // Pointer to the next node
  }
}

// Linked List class
class LinkedList {
  constructor() {
    this.head = null; // Pointer to the first node
    this.tail = null; // Pointer to the last node
  }

  // Insert a new node at the end of the Linked List
  insert(data) {
    const node = new Node(data);

    if (!this.head) {
      // If the Linked List is empty
      this.head = node;
      this.tail = node;
      return;
    }

    // If the Linked List is not empty
    this.tail.next = node;
    this.tail = node;
  }

  // Remove a node from the Linked List
  remove(data) {
    if (!this.head) {
      // If the Linked List is empty
      return;
    }

    if (this.head.data === data) {
      // If the node to be removed is the first node
      this.head = this.head.next;
      return;
    }

    let node = this.head;
    while (node.next) {
      if (node.next.data === data) {
        // If the node to be removed is not the first node
        node.next = node.next.next;
        return;
      }
      node = node.next;
    }
  }

  // Print the elements of the Linked List
  print() {
    let node = this.head;
    while (node) {
      console.log(node.data);
      node = node.next;
    }
  }
}
1349 chars
65 lines

To use this implementation of Linked List:

index.tsx
const list = new LinkedList();
list.insert(10);
list.insert(20);
list.insert(30);
list.remove(20);
list.print(); // Outputs: 10, 30
132 chars
7 lines

In this example, we have implemented a singly Linked List class that can insert and remove nodes, as well as print the elements of the Linked List.

gistlibby LogSnag