I am doing a simple Link List in JavaScript(I’m a newbie) and I Have the following code,
var List = function () {
this.LinkedList = {
"Head": {}
};
};
List.prototype = {
insert: function (element) {
var Node = this.head();
while (Node.hasOwnProperty("Node")) {
Node = this.next(Node);
}
Node["Node"] = {
"element": element
};
},
remove: function (element) {
var Node = this.head();
while (Node.element != element) {
Node = this.next(Node);
}
delete Node.element;
Node = Node.Node; //overwriting Node with Node.Node
},
next: function (Node) {
return Node.Node;
},
head: function () {
return this.LinkedList.Head;
},
getList: function () {
return this.LinkedList;
}
};
When I am doing insertions it is doing fine like,
var myList = new List();
myList.insert(1);
myList.insert(5);
myList.insert(6);
myList.insert(2);
This gives me a List of,
{
"Head": {
"Node": {
"element": 1,
"Node": {
"element": 5,
"Node": {
"element": 6,
"Node": {
"element": 2
}
}
}
}
}
}
Now when I do a delete, it is not giving the right List:
myList.remove(5);
{
"Head": {
"Node": {
"element": 1,
"Node": {
"Node": {
"element": 6,
"Node": {
"element": 2
}
}
}
}
}
}
What I want to get is like this:
{
"Head": {
"Node": {
"element": 1,
"Node": {
"element": 6,
"Node": {
"element": 2
}
}
}
}
}
Any Ideas on how to solve this? Thanks in advance.
It’s because
Node = Node.Nodeis not assigning the next node as the current node. You are merely assigningNode.Nodeto the variableNode. With that, you are NOT overwriting. In a sense, you only get “read privileges”.To get around this and get the benefits of passing references, modify the property of the object your variable is referencing to. That way, you have read and modify privileges, so to speak.
A short example to explain your what happened in your code:
So instead, here’s a simplified approach with a stripped version of the code:
And just as an aside, name your variables, properties and stuff verbosely.