输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
题解
我首先想到的是反转链表,然后将反转的链表的值循环赋值给数组。
后来出现了空指针异常的问题。
问题是因为没有对创建的数组进行初始化大小设置。
public int[] reversePrint(ListNode head) {
if(head == null){
return null;
}
ListNode preNode = null;
ListNode nextNode = null;
ListNode curNode = head;
int j=0;
while (curNode != null){
nextNode = curNode.next;
curNode.next = preNode;
preNode = curNode;
curNode = nextNode;
j++;
}
int[] array = new int[j];
int i = 0;
while (preNode != null){
array[i] = preNode.val;
i++;
preNode = preNode.next;
}
return array;
}
更方便的解法就是使用栈来解了。将链表入栈,获取栈的大小为数组的初始化大小。
循环给数组赋值
public static int[] reversePrint(ListNode head) {
if(head == null){
return null;
}
// 利用栈先进后出的特点来解题
Stack<ListNode> stack = new Stack<>();
while (head != null){
stack.push(head);
head = head.next;
}
int size = stack.size();
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = stack.pop().val;
}
return arr;
}