Quick actions

cmd+k|ctrl+k

Navigation

Languages

DoublyLinkedList

Snippet info

Language

JavaScript

Visibility

public

Author

kishorrathva8298

Created

2022-04-07T21:20:57.757352Z

Updated

2022-04-07T21:21:30.96533Z

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

  append(value) {
    // O(1)
    const newNode = new Node(value);
    newNode.prev = this.tail;
    this.tail.next = newNode;
    this.tail = newNode;
    this.length++;
  }

  prepend(value) {
    // O(1)
    const newNode = new Node(value);
    this.head.prev = newNode;
    newNode.next = this.head;
    this.head = newNode;
    this.length++;
  }

  printList() {
    const array = [];
    let currentNode = this.head;
    while (currentNode !== null) {
      array.push(currentNode.value);
      currentNode = currentNode.next;
    }

    return array;
  }

  insert(index, value) {
    if (index === 0) {
      return this.prepend(value);
    }
    if (index >= this.length) {
      return this.append(value);
    }
    let count = 0;
    let prev = this.head;
    const newNode = new Node(value);
    while (prev.next !== null) {
      if (count === index - 1) {
        newNode.next = prev.next;
        prev.next.prev = newNode;
        newNode.prev = prev;
        prev.next = newNode;
        this.length++;
        break;
      }
      prev = prev.next;
      count++;
    }
  }

  remove(index) {
    if (index === 0) {
      const newHead = this.head.next;
      delete this.head;
      this.head = newHead;
      return;
    }
    let count = 0;
    let prev = this.head;
    while (prev.next !== null) {
      if (count === index - 1) {
        const deleteThis = prev.next;
        delete prev.next;
        deleteThis.next.prev = prev;
        prev.next = deleteThis.next;

        this.length--;
        break;
      }
      prev = prev.next;
      count++;
    }
  }
}

const myDoublyLinkedList = new DoublyLinkedList(10);
console.log(myDoublyLinkedList.printList());
myDoublyLinkedList.append(50);
console.log(myDoublyLinkedList.printList());
myDoublyLinkedList.append(60);
console.log(myDoublyLinkedList.printList());
myDoublyLinkedList.append(70);
console.log(myDoublyLinkedList.printList());
myDoublyLinkedList.append(80);
console.log(myDoublyLinkedList.printList());
myDoublyLinkedList.prepend(1);
console.log(myDoublyLinkedList.printList());
myDoublyLinkedList.insert(1, 99);
console.log(myDoublyLinkedList.printList());
myDoublyLinkedList.remove(0);
console.log(myDoublyLinkedList.printList());
console.log(myDoublyLinkedList);
INFO