Tell us what’s happening:
ive written bad code that passes all the tests. if you try to remove the last node you will see it’s not behaving as expected.
expected behavior desired:
the code for remove method, should set the tail to the second to last element when the last element is removed, using the below code, the last freecodecamp test “The last item should be removable from the list.” should also fail.
Your code so far
[spoiler]
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
// change code above this line
this.add=function(data){
console.clear()
let node= new Node(data)
if(!this.head){
this.head=node
this.tail=node
} else {
let currentNode=this.head;
while(currentNode.next){
currentNode=currentNode.next
}
currentNode.next=node;
node.prev=currentNode;
this.tail=node
}
}
this.remove=function(data){
if(!this.head){return null}
if(!this.head.next&&this.head.data===data){
this.head=null
this.tail=null
return
}
if(this.head.next&&this.head.data==data){
console.log(this.head, 'this.head inside second if block')
console.log('im bbefoere')
this.head=this.head.next
this.head.prev=undefined
return
}
console.log('im reached')
let previousNode;
let currentNode=this.head;
while(currentNode.data!=data){
previousNode=currentNode
currentNode=currentNode.next
}
previousNode.next= currentNode.next
}
};
let double=new DoublyLinkedList()
double.add('1')
double.add('2')
double.add('3')
double.add('4')
console.log(double.head, '= head')
// console.log(double.tail.prev, '= head')
console.log(double.head.next, '= element after the head')
// console.log(double.head.next.next, '= element after the element after the head')
console.log(double.tail, '= tail')
// console.log('removing second')
double.remove('3')
console.log('removing 3')
// double.remove('second')
console.log(double.head, '= head')
// console.log(double.tail.prev, '= head')
console.log(double.head.next, '= element after the head')
console.log(double.head.next.next, '= element after the element after the head')
console.log(double.tail, '= tail')
[/spoiler]
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36
.
Challenge: Create a Doubly Linked List
Link to the challenge: