将数组转换为链表 - 来自 Eloquent Javascript [英] Converting array to Linked list - from Eloquent Javascript

查看:22
本文介绍了将数组转换为链表 - 来自 Eloquent Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我无法理解的书中的挑战之一,或者我的大脑无法分解它.这是解函数:

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?

推荐答案

这里是:

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]);

这篇关于将数组转换为链表 - 来自 Eloquent Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆