publicint[] reversePrint(ListNode head) { // 使用栈,依次出栈 ListNode cur = head; Stack<Integer> stack = new Stack<>(); while (cur.next != null) { stack.push(cur.val); cur = cur.next; } /* * 如果在fori中有stack.size(),会因为pop()出栈操作而导致出循环的次数有变化 * */ int len = stack.size(); int[] res = newint[len]; for (int i = 0; i < len; i++) { res[i] = stack.pop(); } return res; }
思路二:
可以通过方法调用的顺序,使用递归
☕代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicint[] reversePrint(ListNode head) { // 2.尝试递归 ListNode cur = head; ArrayList<Integer> list = new ArrayList<>(); reverse(cur, list); int[] res = newint[list.size()]; int index = 0; for (int num : list) { res[index++] = num; } return res; }