It is one of the challenge in the book I fail to understand, or my brain is unable to break it down. Here is the solution function:
function arrayToList(array) {
var list = null;
for (var i = array.length - 1; i >= 0; i--)
list = {value: array[i], rest: list};
return list;
}
console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
so we are looping the array inversly so first time list should be:
list = {value:20, rest:{value:20, rest:**mind blows here**}}
can any one help me through this process?
reducer can be used to create linked list from array elements.
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
let input = [1, 2, 3];
let head = input.reverse().reduce((acc, curr) => {
if (acc == null) {
acc = new ListNode(curr);
} else {
acc = new ListNode(curr, acc);
}
return acc;
}, null);
console.log(head);
Here it is:
function L(val){
this.val = val;
this.next = null;
}
//We have to develop
/*
L{
val:1,
next:{
val:2,
next: {
val:3,
next: {
val:4,
next:null
}
}
}
}
*/
function createL(a){
let node, temp;
for(let i=a.length-1; i >= 0; i--){
if(!node)
node = new L(a[i]);
else {
temp = new L(a[i]);
temp.next = node;
node = temp;
}
}
return node;
}
createL([1,2,3,4]);
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