代码
/** * 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]; Stack<Integer> stack = new Stack<>(); List<Integer> l = new ArrayList<>(); ListNode cur = head; while(cur != null ) { stack.push(cur.val); cur = cur.next; } while(!stack.isEmpty() ) { l.add(stack.pop()); } return l.stream().mapToInt(Integer::intValue).toArray(); }}
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public int[] reversePrint(ListNode head) { Stack<Integer> stack = new Stack<>(); while (head != null) { stack.push(head.val); head = head.next; } int[] res = new int[stack.size()]; int i = 0; while (!stack.isEmpty()) { res[i ++] = stack.pop(); } return res; }}