I have the following code to convert an array to a linked list:
function arrayToList(array) {
var list = null;
for (var i = array.length - 1; i >= 0; i--)
list = {value: array[i], rest: list};
return list;
}
This code was given to me so I'm trying to understand it. I get the basic intuition/gist of it (I've worked with linked lists, took a data structures class in Java already, understand basics of pointers in C), etc.
However, something's not clicking and I want to make sure I can see what's going on. So let's consider we create a variable, list, referring to memory space whose value is declared to be null. Let's say this "memory address" of this is 0001:
0001: [null] list
So what happens after the first iteration of our loop? This is my interpretation. list now refers to a new chunk of space. That is, by re-defining list in the line:
list = {value: array[i], rest: list};
we created a "new" object that occupies new space. So now we might have:
0001: [null]
0002: [array[i]] list.value
0003: [null] list.rest
(I'm not quite sure where exactly list is "pointing" to now, assuming 0002, though conceptually I guess that's kind of moot in Javascript)
Is this understanding correct? I'm used to thinking of data structures a la Java, where an object like list has already-defined blocks of space every time an instance is created. I've worked with Python but have not built linked lists with it before. From this I assume a language like Javascript is fluid in that you can just have a variable be null, then have it refer to a hash, then when you set it to be another hash it creates a "new" hash, etc.
Thanks!