Tell us what’s happening:
.remove
method is called only once for deleting from an empty list. While two last suites (The first item should be removable from the list. The last item should be removable from the list.) definitely require it, not only .add
Your code so far
var Node = function(data, prev) {
this.data = data;
this.prev = prev;
this.next = null;
};
var DoublyLinkedList = function() {
console.log({created: true})
this.head = null;
this.tail = null;
// Only change code below this line
Object.assign(this, {
length: 0,
add: function(el) {
console.log({add: el, length: this.length})
this.length += 1
if (this.length === 1) {
const node = new Node(el)
this.head = node
this.tail = node
return node
} else {
const node = new Node(el, tail)
tail.next = node
tail = node
return node
}
},
remove: function (el) {
const {length} = this
console.log({remove: el, length})
if (length === 0)
return null
let pre = null
, {head: pointer} = this
while (pointer !== null) {
if (pointer.data !== el) {
pre = pointer
} else {
this.length -= 1
const {next} = pointer
if (pre === null) {
this.head = next
next.prev = undefined
} else {
next.prev = pre
pre.next = next
}
}
pointer = pointer.next
}
}
})
// Only change code above this line
};
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:81.0) Gecko/20100101 Firefox/81.0
.
Challenge: Create a Doubly Linked List
Link to the challenge: