classSolution{publicint[]reversePrint(ListNode head){if(head == null)returnnewint[0];// 用一个辅助栈来实现
Stack<Integer> stack =newStack<>();
stack.add(head.val);int total =1;while(head.next != null){
stack.add(head.next.val);
head = head.next;
total++;}int[] res =newint[total];for(int i =0; i < total; i++){
res[i]= stack.pop();}return res;}}
思路二:先计数,然后再填充
classSolution{publicint[]reversePrint(ListNode head){int total =0;
ListNode tmp = head;while(tmp != null){
total++;
tmp = tmp.next;}int[] res =newint[total];for(int i = total -1; i >=0; i--){
res[i]= head.val;
head = head.next;}return res;}}