使用 Java 将数组转换为单链表可分三步:创建单链表节点类、遍历数组并创建节点、返回链表头,示例中将数组 [1, 2, 3, 4, 5] 转换为单链表 1 -> 2 -> 3 -> 4 -> 5 -> null。
如何使用 Java 将数组转换为单链表
回答:
使用 Java 将数组转换为单链表可以采用以下步骤:
步骤 1:创建单链表节点类
立即学习“Java免费学习笔记(深入)”;
public class Node<T> { private T data; private Node<T> next; public Node(T data) { this.data = data; } public T getData() { return data; } public Node<T> getNext() { return next; } public void setNext(Node<T> next) { this.next = next; } }
步骤 2:遍历数组并创建节点
Node<Integer> head = null; Node<Integer> current = null; for (int value : array) { Node<Integer> 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<Integer> head = convertArrayToLinkedList(array);
输出:
1 -> 2 -> 3 -> 4 -> 5 -> null
以上就是java怎么把数组存到单链表的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号