Doubly Linked List Implementation

·

2 min read

class DoublyLinkedList{
  constructor(value){
    this.head = {
      value: value,
      prev: null,
      next: null
    }
    this.tail = this.head
    this.length= 1
  }

append(value){
  const newNode = {
    value: value,
    prev: null,
    next: null
  };
  // previous connection
  newNode.prev = this.tail
  // next connection
  this.tail.next = newNode
  this.tail = newNode
  this.length++
  return this  
}
prepend(value){
  const newNode = {
    value: value,
    prev: null,
    next:  null
  };
  newNode.next = this.head
  this.head.prev = newNode
  this.head = newNode;
  this.length++
}
  printList() {
    const array = [];
    let currentNode = this.head;
    while (currentNode !== null) {
      array.push(currentNode.value);
      currentNode = currentNode.next;
    }
    return console.log(array);
  }


insert(index  , value)
  {
    if(index >= this.length){
      return this.append(value)
    }
    const newNode = {
      value: value,
      prev: null,
      next: null,
    };
     const leader = this.traverseToIndex(index - 1);
     const follower = leader.next
    leader.next = newNode
    newNode.prev = leader
    newNode.next = follower
    follower.prev = newNode
    this.length++
    return this.printList()
  }

  traverseToIndex(index) {
    //Check parameters
    let counter = 0;
    let currentNode = this.head;
    while (counter !== index) {
      currentNode = currentNode.next;
      counter++;
    }
    return currentNode;
  }

  remove(index) {
    // Check Parameters
    if (index < 0 || index >= this.length) {
      console.log("Invalid index");
      return;
    }
    let currentNode = this.head;
    if (index === 0) {
      // If removing the head node
      this.head = currentNode.next;
      if (this.head) {
        this.head.prev = null;
      } else {
        // If the list becomes empty
        this.tail = null;
      }
    } else if (index === this.length - 1) {
      // If removing the tail node
      currentNode = this.tail;
      this.tail = currentNode.prev;
      this.tail.next = null;
    } else {
      // Removing a node in the middle
      currentNode = this.traverseToIndex(index);
      currentNode.prev.next = currentNode.next;
      currentNode.next.prev = currentNode.prev;
    }
    this.length--;
    return this.printList();
  }

}

Implementation Of Doubly Linked List In Javascript