Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting array to Linked list - from 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?

like image 653
Haris Khan Avatar asked Oct 18 '25 09:10

Haris Khan


2 Answers

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);
like image 84
hasan.in Avatar answered Oct 19 '25 22:10

hasan.in


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]);
like image 34
Probosckie Avatar answered Oct 19 '25 22:10

Probosckie