create a linked list in javascript

Below is an example implementation of a singly linked list in JavaScript:

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

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

  addNode(data) {
    let node = new Node(data);

    if (!this.head) {
      this.head = node;
    } else {
      let current = this.head;

      while (current.next) {
        current = current.next;
      }

      current.next = node;
    }

    this.size++;
  }

  removeNode(data) {
    let current = this.head;
    let previous = null;

    while (current !== null) {
      if (current.data === data) {
        if (!previous) {
          this.head = current.next;
        } else {
          previous.next = current.next;
        }
        this.size--;
        return current.data;
      }

      previous = current;
      current = current.next;
    }

    return null;
  }

  getSize() {
    return this.size;
  }

  printList() {
    let current = this.head;

    while (current !== null) {
      console.log(current.data);
      current = current.next;
    }
  }
}
1043 chars
67 lines

This implementation uses a Node class to represent each node of the linked list, and a LinkedList class to implement the list itself. The addNode method inserts a new node at the end of the list, and the removeNode method removes the first node with a given data value. The getSize method returns the size of the list, and the printList method prints the data value of each node in the list.

gistlibby LogSnag