# 数组转换为链表|博客系列

> 本文介绍如何将数组转换为链表，包含递归和非递归两种实现方法，适合前端开发者学习数据结构与算法面试题。

- 原文：https://feinterview.poetries.top/docs/fe-blog-docs/blog-docs/data-struct/29-%E6%95%B0%E7%BB%84%E8%BD%AC%E6%8D%A2%E4%B8%BA%E9%93%BE%E8%A1%A8
- 来源：前端进阶之旅（feinterview.poetries.top）
- 更新：2025.10.25

---

### 题目描述

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

例如：

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

### 解题思路

1. 每一个节点都是一个`NodeList`;
2. 数组的尾部是链表的头部，从数组的尾部开始取出数字创建节点，并更新数组的长度；
3. 可以用递归或者非递归两种方式实现，但是终止的条件都是判断数组的长度是否为0了。

### coding

#### 递归

```javascript
/**
 * 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)
}
```

#### 非递归

```javascript
/**
 * 将数组转换为链表
 */
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
}
```

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

**测试代码**

```javascript
transformArrayToList([4, 3, 2])
// { val: 2, next: { val: 3, next: { val: 4, next: null } } }
```
