把数组转成链表的方法java
在Java中,可以使用链表的节点类来表示链表,并通过遍历数组来构建链表。以下是一个示例代码:
public class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class Solution {
public ListNode arrayToList(int[] arr) {
if (arr == null || arr.length == 0) {
return null;
}
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
for (int i = 0; i < arr.length; i++) {
curr.next = new ListNode(arr[i]);
curr = curr.next;
}
return dummy.next;
}
}
使用示例:
int[] arr = {1, 2, 3, 4, 5};
Solution solution = new Solution();
ListNode head = solution.arrayToList(arr);
在上面的示例中,我们首先创建一个虚拟头节点dummy,然后遍历数组arr,将数组中的每个元素都构建成一个链表节点,并将其连接到当前节点的next指针上。最后返回虚拟头节点的next指针,即为转换后的链表头节点
原文地址: https://www.cveoy.top/t/topic/iqdP 著作权归作者所有。请勿转载和采集!