Create a Doubly Linked List: doesn't pass last two test cases

Tell us what’s happening:
My code isn’t passing the test cases, even though I am taking care of cases where the head or tail is removed.

Your code so far


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 = function(element) {
    var node = new Node(element, null);
    if (this.head === null) this.head = node;
    if (this.tail === null) {
      this.tail = this.head;
      while (this.tail.next !== null) this.tail = this.tail.next;
    }
    else {
      var ptr = this.head;
      while (ptr !== this.tail && this.tail !== null) ptr = ptr.next;
      this.tail.next = node;
      node.prev = this.tail;
      this.tail = node;
    }
  }

  this.remove = function(element) {
    var ptr = this.head;
    if (this.head === null) return null;
    if (this.head.element === element) {
      this.head = this.head.next;
      this.head.prev = null;
    }
    if (this.tail.element === element) {
      this.tail = this.tail.prev;
      this.tail.next = null;
    }
    while (ptr !== null) {
      if (ptr.element === element) {
        ptr.prev.next = ptr.next;
        ptr.next.prev = ptr.prev;
      }
      ptr = ptr.next;
    }
  }
  // change code above this line
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/data-structures/create-a-doubly-linked-list/

1 Like

Please post the solution if you have found one.:pray:

@dPatel88 If you are stuck on this challenge, instead of asking for the solution, just create a new thread with the code you have tried and we can help guide you to a solution.

Done.

When removing the last element, you are not properly setting the tail.