Linked List nested Object
Input Should be like this
var ii = {"val":"1","next":{"val":"2","next":{"val":"3","next":{"val":"4","next":{"val":"5","next":null}}}}};
Output should be like [1,2,3,4,5]
Linked List nested Object
Input Should be like this
var ii = {"val":"1","next":{"val":"2","next":{"val":"3","next":{"val":"4","next":{"val":"5","next":null}}}}};
Output should be like [1,2,3,4,5]
A little fancier demonstrating a recursive function call, as may have been the point of the exercise and utilizing Array.reduce().
var ii = {
"val":"1", "next":{
"val":"2", "next":{
"val":"3", "next":{
"val":"4", "next":{ "val":"5", "next":null }
}
}
}
};
const process = obj => {
const remap = (acc,[k,v]) => ([
...acc,
...(( k === 'val') ? v : (v === null)
? [] : Object.entries(v).reduce(remap,[]))
]);
return Object.entries(obj).reduce(remap,[]);
};
console.log(process(ii));
Whist fancy, it's not as efficient. So still keeping with "non destructive" you can take a clone of the object and still recurse:
var ii = {
"val":"1", "next":{
"val":"2", "next":{
"val":"3", "next":{
"val":"4", "next":{ "val":"5", "next":null }
}
}
}
};
const process = obj => (({ val, next }) =>
[ val, ...((next !== null) ? process(next): []) ])(obj);
console.log(process(ii));
Even cleaner and effectively just as fast as the while, and of course "non-destructive" to the original content since it's all locally scoped.
You can create an empty array and push the data into it while going through the list. I am using JavaScript to solve your problem.
let ii = {"val":"1","next":{"val":"2","next":{"val":"3","next":{"val":"4","next":{"val":"5","next":null}}}}};
let array = [];
//Your linked list
let head = ii;
//Until the list data reaches null continue doing the codes below
while(head !== null){
//Get the data from list and push it into your array.
array.push(head.val);
//after pushing data move to the next list by changing head position
head = head.next;
}
//return the array after all data is pushed in
return array;