# 题目描述

输入一个数组,将其转换为一个链表(数组的最后一项为链表的头部)

例如:

输入 [4, 3, 2]
输出 2 -> 3 -> 4

# 解题思路

  1. 每一个节点都是一个NodeList;
  2. 数组的尾部是链表的头部,从数组的尾部开始取出数字创建节点,并更新数组的长度;
  3. 可以用递归或者非递归两种方式实现,但是终止的条件都是判断数组的长度是否为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 // 由于list的第一项的val是null, 所以这里要返回next
}

个人比较喜欢用非递归的方式。

测试代码

transformArrayToList([4, 3, 2])
// { val: 2, next: { val: 3, next: { val: 4, next: null } } }
阅读全文