Data Structures: Create a Doubly Linked List

Help me! I get the following error:
Each node keeps track of the previous node.

var Node = function (data, prev) {
  this.data = data;
  this.prev = prev;
  this.next = null;
};
var DoublyLinkedList = function () {
  this.head = null;
  this.tail = null;
  // change code below this line
  this.add = (element) => {
    let newNode = new Node(element, null);
    if (this.head === null) {
      this.head = newNode;
      this.tail = this.head;
    }
    this.tail.next = newNode;
    newNode.prev = this.tail;
    this.tail = newNode;
  }
  this.remove = (item) => {
    let nextNode;
    let prevNode;
    if (this.head === null) return null;

    if (this.head.data === item) {
      this.head = this.head.next;
      this.head.prev = null;
    } else if (this.tail.data === item) {
      this.tail = this.tail.prev;
      this.tail.next = null;
    } else {
      let currentNode = this.head.next;
      while (currentNode.next !== null) {
        if (currentNode.data === item) {
          prevNode = currentNode.prev;
          nextNode = currentNode.next;
          prevNode.next = nextNode;
          nextNode.prev = prevNode;
          console.log(`[${currentNode.prev.data} ${currentNode.data} ${currentNode.next.data}]`);
        }
        currentNode = currentNode.next;
      }
    }
  };
  // change code above this line
};

let dbl = new DoublyLinkedList();
dbl.add('gato');
dbl.add('kelvin');
dbl.add('dog');
dbl.add('aldo');
dbl.add('perro');
dbl.add('ave');
dbl.remove('aldo');

I have solved it!
My mistake was that the ‘prev’ pointer pointed to itself, like this one:

head -> [gato <- gato -> kelvin]
Node 1 [gato <- kelvin -> dog]
Node 2 [kelvin <- dog -> aldo]
Node 3 [dog <- aldo -> perro]
Node 4 [aldo <- perro -> ave]
[perro <- ave -> null] <- tail

when should it be:

head -> [null <- gato -> kelvin]
Node 1 [gato <- kelvin -> dog]
Node 2 [kelvin <- dog -> aldo]
Node 3 [dog <- aldo -> perro]
Node 4 [aldo <- perro -> ave]
[perro <- ave -> null] <- tail

1 Like