Tell us what’s happening:
Not exactly sure what I’m doing wrong. I’ve whiteboarded the problem and visualized my code using pythontutor, and while it makes sense to me, it’s not producing a correct result on the website.
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 = (index) => {
if (index < 0 || index >= length) {
return null
}
if (index === 0) {
let removedNode = head
head = head.next
length--
return removedNode.element
} else {
let count = 1
let prev = head
let curr = prev.next
while (count + 1 !== index) {
prev = prev.next
curr = curr.next
count++
}
prev = prev.next
curr = curr.next
prev.next = curr.next
length--
return curr.element
}
}
// Only change code above this line
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36
Challenge: Data Structures - Remove Elements from a Linked List by Index
Link to the challenge: