将数组转换为链接列表-从雄辩的Javascript [英] Converting array to Linked list - from Eloquent Javascript

查看:60
本文介绍了将数组转换为链接列表-从雄辩的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?

推荐答案

reducer可用于根据数组元素创建链接列表.

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

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

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