Currently, I am working on converting arrays into linked lists and vice versa. The challenge I am facing is that when I try to log the linked list I have created, it shows incorrect values. However, when I convert the same linked list back into an array, the console log displays the correct values.
For example, in the code snippet below, when I use listToArray() function, I correctly get the output [1, 2, 3, 4, 5]. But when I use arrayToList() function, the output is { value: 1, rest: { value: 2, rest: { value: 3, rest: [Object] } } }. This makes me wonder what happened to the values 4 and 5. Given that listToArray() uses the same list generated from arrayToList(), shouldn't all values be intact?
var array = [1, 2, 3, 4, 5];
var arrayToList = function(arr) {
var list = {};
var head = list;
for (i = 0; i < arr.length; i += 1) {
list.value = arr[i];
list.rest = {};
if (i == arr.length - 1) {
list = null;
} else {
list = list.rest;
}
}
return head;
}
var listToArray = function(list) {
var arr = [];
var index = 0;
while(list.rest != null) {
arr[index] = list.value;
list = list.rest;
index += 1;
}
return arr;
}
console.log(listToArray(arrayToList(array)));
console.log(arrayToList(array));