使用 Java 将数组转换为单链表可分三步:创建单链表节点类、遍历数组并创建节点、返回链表头,示例中将数组 [1, 2, 3, 4, 5] 转换为单链表 1 -> 2 -> 3 -> 4 -> 5 -> null。

如何使用 Java 将数组转换为单链表
回答:
使用 Java 将数组转换为单链表可以采用以下步骤:
步骤 1:创建单链表节点类
立即学习“Java免费学习笔记(深入)”;
public class Node{ private T data; private Node next; public Node(T data) { this.data = data; } public T getData() { return data; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } }
步骤 2:遍历数组并创建节点
Nodehead = null; Node current = null; for (int value : array) { Node newNode = new Node<>(value); if (head == null) { head = newNode; current = head; } else { current.setNext(newNode); current = current.getNext(); } }
步骤 3:返回链表头
return head;
示例:
int[] array = {1, 2, 3, 4, 5};
Node head = convertArrayToLinkedList(array); 输出:
1 -> 2 -> 3 -> 4 -> 5 -> null











