# 题目描述
输入一个数组,将其转换为一个链表(数组的最后一项为链表的头部)
例如:
输入 [4, 3, 2]
输出 2 -> 3 -> 4
@前端进阶之旅: 代码已经复制到剪贴板
# 解题思路
- 每一个节点都是一个
NodeList; - 数组的尾部是链表的头部,从数组的尾部开始取出数字创建节点,并更新数组的长度;
- 可以用递归或者非递归两种方式实现,但是终止的条件都是判断数组的长度是否为0了。
# coding
# 递归
/**
* Definition for singly-linked list.
*/
function ListNode(val) {
this.val = val;
this.next = null;
}
/**
* 将数组转换为链表
*/
function transformArrayToList (array) {
function createList (array) {
if (array.length === 0) return null // 若数组长度为0则返回null
let val = array.pop() // 从尾部取出值(第一个值为链表的头部)
let list = new ListNode(val) // 创建一个节点
list.next = createList(array) // 节点的next则调用剩下的数组
return list
}
return createList(array)
}
@前端进阶之旅: 代码已经复制到剪贴板
# 非递归
/**
* 将数组转换为链表
*/
function transformArrayToList (array) {
let list = new ListNode(null) // 先定义一个链表节点
let node = list // 当前节点
while (array.length > 0) { // 若数组长度为0则终止循环
let val = array.pop() // 从尾部取出值(第一个值为链表的头部)
node.next = new ListNode(val) // 节点的next值为一个新的节点
node = node.next // 将当前节点赋值为节点的next
}
return list.next 