"Create a Doubly Linked List" solution

What is your hint or solution suggestion?

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){
    if(this.head){
      var newest = new Node(element,this.tail)
      this.tail.next = newest;
      this.tail = newest;
    }
    else{
      this.head = new Node(element,null)
      this.tail = this.head;
    }
  }
  this.remove = function(element){
    if(this.head == null) {
      return null;
    }
    else if (this.head.data == element) {
      this.head.data = null;
    }
    else if(this.tail.data == element) {
      this.tail.data = null;
    }
  }
  // change code above this line
};

Code Explanation

The DoublyLinkedList object must have the following structure:

{ head: 
   { data: 'one',
     prev: null,
     next: { data: 'two', prev: [Circular], next: [Object] } },
  tail: 
   { data: 'four',
     prev: { data: 'three', prev: [Object], next: [Circular] },
     next: null },
  add: [Function],
  remove: [Function] }

If the object is null and we wish to add an element, this.head and this.tail are both equal to each other as Node objects. After adding the first element, a new Node is created with the data and prev elements, which is set using this.tail.next = newest.

Since this.head = this.tail, this.head.next also changes to the same value. To reverse this.tail after adding an element so the last element comes first, we set this.tail = newest.

In the remove method, the first case is if this.head == null, where null is returned, indicating that the list was empty. The other two cases focus on the first and last list items.

Relevant Links

Challenge: Create a Doubly Linked List

Link to the challenge: