var Node = function(data, prev) {
this.data = data;
this.prev = prev;
this.next = null;
};
var DoublyLinkedList = function() {
this.head = null;
this.tail = null;
// Only change code below this line
this.add = function (data) {
let node = new Node(data, this.tail);
if (!this.head) {
this.head = node;
this.tail = node;
} else {
let tempNode = this.tail;
tempNode.next = node;
this.tail = node;
}
};
this.remove = function (data) {
if (this.head === null) return null;
let tempNode = this.head;
while (tempNode !== this.tail) {
if (tempNode.data === data) {
if (tempNode === this.head) {
this.head = tempNode.next;
tempNode.next.prev = null;
} else {
let prevNode = tempNode.prev;
prevNode.next = tempNode.next;
}
}
tempNode = tempNode.next;
}
if (tempNode.data === data) {
this.tail = tempNode.prev;
tempNode.prev.next = null;
}
console.log(this.tail, "tail")
console.log(this.head, "head")
};
// Only change code above this line
};
const p = new DoublyLinkedList()
console.log(p.add(3))
console.log(p.add(2))
console.log(p.add(4))
console.log(p.add(5))
console.log(p.remove(2))
result in console:
{ data: 5,
prev:
{ data: 4,
prev: { data: 2, prev: [Object], next: [Circular] },
next: [Circular] },
next: null } tail
{ data: 3,
prev: null,
next:
{ data: 4,
prev: { data: 2, prev: [Circular], next: [Circular] },
next: { data: 5, prev: [Circular], next: null } } } head
Above is given solution for ‘create a doubly linked list’ and I’m a bit confused about the result given when I console.log ‘this.tail’ and ‘this.head’. I added elements to linked list and then removed element 2 BUT that node still shows up in console.log result. It’s referenced by prev of 4 in head, and prev of 4 in tail, so is it still there? And does this solution not actually remove that element or am I missing something? With the solution I came up, I was able to pass tests and also got more of the result I was expecting (where node with data: 2 is not referenced at all) when adding and removing same nodes and using console.log in same place, but in my code. My codes result in console:
const p = new DoublyLinkedList()
console.log(p.add(3))
console.log(p.add(2))
console.log(p.add(4))
console.log(p.add(5))
console.log(p.remove(2))
result:
{ data: 5,
prev:
{ data: 4,
prev: { data: 3, prev: null, next: [Circular] },
next: [Circular] },
next: null } tail
{ data: 3, prev: null, next: [Circular] } head
Pretty confused here. Thanks for any help and hopefully not too confusing!
link to problem:
problem link