add a method removeat on linkedlist. in javascript

Here's an example implementation of removeAt method for LinkedList in JavaScript:

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

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

  add(element) {
    var node = new Node(element);

    var current;

    if (this.head == null) this.head = node;
    else {
      current = this.head;

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

      current.next = node;
    }
    this.size++;
  }

  removeAt(index) {
    if (index > 0 && index > this.size) return -1;
    else {
      var current = this.head;
      var previous = current;
      var count = 0;

      if (index === 0) {
        this.head = current.next;
      } else {
        while (count < index) {
          count++;
          previous = current;
          current = current.next;
        }

        previous.next = current.next;
      }
      this.size--;

      return current.element;
    }
  }
}
930 chars
56 lines

The removeAt method takes an index as an argument, then checks if the index is within the bounds of the LinkedList size. It then traverses the list until it finds the node at the specified index, reassigns the next pointer of the previous node to the next node to delete. It then decrements the size of the list and returns the element of the deleted node.

You can use it like this:

index.tsx
let list = new LinkedList();

list.add(1);
list.add(2);
list.add(3);

console.log(list.removeAt(1)); // remove node at index 1, should return 2
console.log(list); // { head: Node { element: 1, next: Node { element: 3, next: null } }, size: 2 }
244 chars
9 lines

related categories

gistlibby LogSnag