尝试了一下,用递归写不出来,没有办法使用递归控制下标的移动。只能用循环了,应该还是可以使用递归的。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
if (head == null) {
return new int[0];
}
if (head.next == null) {
int[] ints = {head.val};
return ints;
}
List<Integer> container = new ArrayList<>();
ListNode temp = head.next;
while ( temp!= null) {
container.add(temp.val);
temp = temp.next;
}
int j = 0;
int[] arr = new int[container.size() + 1];
for (int i = container.size() - 1; i >= 0; i--) {
arr[j++] = container.get(i);
}
arr[j] = head.val;
return arr;
}
}