我想用Java编写LinkedList的Print Reverse函数。我是这样写的,但是不行。编译器警告 NullPointerException
。
void ReversePrint(Node head) {
int[] array = null;
int i = 0;
Node tmp;
for (tmp = head; tmp != null; tmp = tmp.next) {
array[i] = tmp.data;
i++;
}
for(int j = i; j >= 0; j--){
System.out.println(array[j]);
}
}
最佳答案
您会收到 NullPointerException
,因为变量 array
为 null
:
int[] array = null;
在此处使用它之前,您需要先用一个值对其进行初始化:
array[i] = tmp.data;
例如,使用这样的语句:
int[] array = new int[size];
其中size
可能应该是您的LinkedList
的大小。如果您出于某种原因不知道大小,您可以使用 ArrayList 类,该类实现具有动态大小的数组(它会猜测一个大小,如果您超出了该大小, ,它将重新分配一个更大的数组并复制所有内容等等)。
这是使用所述 ArrayList
的版本:
// Method names should start with a lower-case letter
void reversePrint(Node head) {
// Initialize an empty ArrayList
ArrayList<Integer> dataList = new ArrayList<>();
int i = 0;
Node tmp;
for (tmp = head; tmp != null; tmp = tmp.next) {
// Set the element at position i of the ArrayList
dataList.set(i, tmp.data);
i++;
}
// See next comment
i--;
for(int j = i; j >= 0; j--){
// Get the element at position j of ArrayList and print it
System.out.println(dataList.get(j));
}
}
请注意,您还会遇到 IndexOutOfBoundException
,因为到达打印循环时您的 i
太大了 1
。这是因为您还在第一个循环的最后一次迭代中增加了它:
// Suppose last iteration, i is (list.size() - 1) then
for (tmp = head; tmp != null; tmp = tmp.next) {
array[i] = tmp.data;
// i is now list.size()
i++;
}
循环之间需要一个 i--
或循环初始化中的 int j = i - 1
。
如果您要实现双向链接列表,而不仅仅是单链接列表,请注意,您不需要先在数组中记录值。然后,您可以从 tail
开始并跟随 tmp.prev
指针直接打印这些值。
关于java - 在链表中打印反向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46790719/