Here's the basic code
function ListNode(x) {
this.value = x;
this.next = null;
}
function linkedList(arr){
let list = new ListNode(arr[0]);
let selectedNode = list;
for(let i = 1; i < arr.length; i++){
selectedNode.next = new ListNode(arr[i]);
selectedNode = selectedNode.next
}
return list
}
l = [3, 1, 2, 3, 4, 5];
console.log(linkedList(l));
For some reason, it just works. I don't get how the 'list' variable is changing/updating in linkedList(arr) function. I see selectedNode = list, but list never changes. list initializes with the constructor new ListNode(arr[0]) but after that, the only variable that's changing is selectedNode. There isn't even code for list.next to change to something.
So how is it that return list returns the full linked list?
function linkedList(arr){
return arr.reduceRight((next, value) => ({value, next}), null);
}
l = [3, 1, 2, 3, 4, 5];
console.log(linkedList(l));
you don't need the class ListNode
for such a simple object.
When you do this let selectedNode = list;
two variables are pointing to the same value in memory, in this case, list
and selectedNode
. So, the chain of modifications starts with list and downstream adding new linked nodes.
The author has initialized the selectedNode
with list
as a starting point (root node) of the linked list.
This how looks like the memory with this let selectedNode = list;
+-----------------+------------------+
| list | selectedNode |
+-----------------+------------------+
| | | |
| {value: 3, | | |
| next: null } <---------+ |
| | |
+-----------------+------------------+
So, every iteration will modify the same list
object because the next node is bound/linked with the previous nodes:
selectedNode.next = new ListNode(arr[i]); i = 1
+-------------------+------------------+
| list | selectedNode |
+-------------------+------------------+
| | | |
| { | | |
| value: 3, | Points to | |
| next: { | next | |
| value: 1 <------------+ |
| next: null | |
| } | |
| } | |
| | |
+-------------------+------------------+
selectedNode.next = new ListNode(arr[i]); i = 2
+-----------------------+------------------+
| list | selectedNode |
+-----------------------+------------------+
| | | |
| { | | |
| value: 3, | | |
| next: { | | |
| value: 1 | Points to | |
| next: { | next | |
| value: 2, <------------+ |
| next: null | |
| } | |
| } | |
| } | |
| | |
+-----------------------+------------------+
And so on.
When you assign an object type to a variable, the variable's value isn't the actual object but rather a reference to it. Therefore, when you do selectedNode = list
both variables reference the same object and any changes to this object, using any of the references to it, will be visible from any of its references.
In short: the list
variable doesn't change but the object it's referencing does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With