用递归也行,但本质也是先入后出,所以用了双向列表(栈也行),注意for循环时,不能用list的长度,因为在pop的时候长度会变小,导致结果错误,要用数组的length
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> list = new LinkedList<>();
while(head != null){
list.addLast(head.val);
head = head.next;
}
int[] res = new int[list.size()];
for(int i=0; i<res.length; i++){
res[i] = list.removeLast();
}
return res;
}
}