2. 遍历链表,将每个节点的值赋给数组的相应位置。
```java
// 定义链表节点类
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
// 将链表转换为数组的方法
public static int[] listToArray(ListNode head) {
// 计算链表长度
int length = 0;
ListNode current = head;
while (current != null) {
length++;
current = current.next;
}
// 创建数组
int[] array = new int[length];
// 遍历链表,将值赋给数组
current = head;
for (int i = 0; i < length; i++) {
array[i] = current.val;
current = current.next;
}
return array;
}
使用这个方法,你可以将链表中的所有数据录入到数组中。如果你需要将链表中的数据录入到其他类型的数组中,比如 `Integer[]`,你可以使用类似的方法,只需将 `int[]` 替换为相应的类型即可。