剑指 Offer 06. 从尾到头打印链表
res
数组class Solution { int[] res; int index = 0; public int[] reversePrint(ListNode head) { // 先统计链表的总节点数量 int count = 0; ListNode temp = head; while (temp != null) { count++; temp = temp.next; } res = new int[count]; // 进行递归 help(head); // 输出结果 return res; } public void help(ListNode node) { if (node == null) { return; } help(node.next); res[index++] = node.val; } }
pop
弹出来放到res
数组中即可(因为是先进先出,所以此时栈的最后一个元素要先弹出,因此可以实现从尾到头遍历)class Solution { public int[] reversePrint(ListNode head) { // 将链表的元素依次入栈 LinkedList<Integer> stack = new LinkedList<>(); while (head != null) { stack.push(head.val); head = head.next; } int[] res = new int[stack.size()]; // 将栈元素弹出放到res中 int index = 0; while (!stack.isEmpty()) { res[index++] = stack.pop(); } return res; } }