Har*_*han 3 javascript arrays 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;
}
console.log(arrayToList([10, 20]));
// ? {value: 10, rest: {value: 20, rest: null}}
Run Code Online (Sandbox Code Playgroud)
所以我们反向循环数组,所以第一次列表应该是:
list = {value:20, rest:{value:20, rest:**mind blows here**}}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我完成这个过程吗?
has*_*.in 15
reducer 可用于从数组元素创建链表。
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);Run Code Online (Sandbox Code Playgroud)
这里是:
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]);
Run Code Online (Sandbox Code Playgroud)