【题目本意:将数组结构数据转成链表结构,当时没看懂…呜呜…】
输入:
var arr = [
{id : 1, parents : null},
{id : 2 , parents : 1},
{id : 3 , parents : 2},
]
输出:
var obj = {
obj1: {
id:1,
parents:null,
charld:{
id:2,
parents:1,
charld: {
id:3,
parents:2,
}
}
}
}
function arrayTolist(ary) {
if (!ary.length) {
return null
}
var node
var head = { id: ary[0].id, parents: null }
var preNode = head
for (var i = 1; i < ary.length; i++) {
node = { id: ary[i].id, parents: preNode.id }
preNode.child = node
preNode = node
}
return head
}
PS:顺便实现链表转数组
function listToArray(obj) {
if (!obj) {
return []
}
var result = []
while (obj) {
result.push({ id: obj.id, parents: obj.parents })
obj = obj.child
}
return result
}
转载:https://blog.csdn.net/miaomiao_1024/article/details/101469569
查看评论