Tell us what’s happening:
I am unable to pass the following tests ,
Your removeAt method should remove the element at the specified index from the linked list.
When only one element is present in the linked list, your removeAt method should remove and return the element at specified index, and reduce the length of the linked list.
Your removeAt method should return the element of the removed node.
please help me make corrections in my code.
Your code so far
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){
this.element = element;
this.next = null;
};
this.size = function(){
return length;
};
this.head = function(){
return head;
};
this.add = function(element){
var node = new Node(element);
if(head === null){
head = node;
} else {
var currentNode = head;
while(currentNode.next){
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
// Only change code below this line
this.removeAt = function(index){
if(index === 1){
var temp = head;
head = null; //remove
length--; //reduce
return temp.element; //return
}
if(index < 1 || index >= length){
return null;
}
var current = head;
var prev;
let i = 0;
while(i < index){
prev = current;
current = current.next;
i--;
}
prev.next = current.next;
current.next = null;
length--;
return current.element;
}
// Only change code above this line
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0
.
Challenge: Remove Elements from a Linked List by Index
Link to the challenge: