输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
/**
Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
/
class Solution {
public int[] reversePrint(ListNode head) {
ArrayList<Integer> arrayList = new ArrayList<>();
while(head.next!=null){
arrayList.add(head.val);
head=head.next;
}
arrayList.add(head.val);
int n=arrayList.size();
Object[] arr= new Integer[n];
arr= arrayList.toArray();
int[] arr1 = new int[n];
for (int i = 0; i<n ; i++) {
arr1[i]= (int) arr[n-i-1];
}
return arr1;
}
}
已完成
执行用时:0 ms
输入
[1,3,2]
输出
[2,3,1]
预期结果
[2,3,1]
能执行 但是提交会报错
java.lang.NullPointerException: Cannot read field "next" because "" is null
at line 14, Solution.reversePrint
at line 57, DriverSolution.helper
at line 82, Driver.main
class Solution {
public int[] reversePrint(ListNode head) {
ArrayList<Integer> arrayList = new ArrayList<>();
while(head!=null){
arrayList.add(head.val);
head=head.next;
}
int n=arrayList.size();
Object[] arr= new Integer[n];
arr= arrayList.toArray();
int[] arr1 = new int[n];
for (int i = 0; i<n ; i++) {
arr1[i]= (int) arr[n-i-1];
}
return arr1;
}
}
改成上面就不会报错了,为啥会空指针,求解