Tell us what’s happening:
I understand the logic of adding removing and searching elements but if I declare
var currentNode = head;
I think of it as a variable named currentNode with value of this.head and that’s it. But it appears that currentNode is actually a node which has .next and .element. Please explain and it would be really helpful if you can attach some link where I can read up these concepts.
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++;
};
this.remove = function(element){
var currentNode = head;
var previousNode;
if(currentNode.element === element){
head = currentNode.next;
} else {
while(currentNode.element !== element) {
previousNode = currentNode;
currentNode = currentNode.next;
}
previousNode.next = currentNode.next;
}
length --;
};
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0
.
Challenge: Search within a Linked List
Link to the challenge: