剑指 Offer 06. 从尾到头打印链表

image.png

递归

  1. public class Solution {
  2. public int[] reversePrint(ListNode head) {
  3. // 用于存储结果
  4. List<Integer> list = new ArrayList<>();
  5. // 递归方法
  6. recursion(head, list);
  7. // 将 List 转化为 int[]
  8. int[] result = new int[list.size()];
  9. for (int i = 0; i < list.size(); i++) {
  10. result[i] = list.get(i);
  11. }
  12. return result;
  13. }
  14. /**
  15. * 递归打印,思路类似二叉树后序遍历
  16. * @param node 结点
  17. * @param list 存储结果
  18. */
  19. private void recursion(ListNode node, List list) {
  20. if (node != null) {
  21. recursion(node.next, list);
  22. // 在递归调用的的下方打印
  23. list.add(node.val);
  24. }
  25. }
  26. }

递归2

增加记录链表长度,简化掉 List 转数组的操作
image.png

  1. class Solution {
  2. // 记录返回结果
  3. private int[] res;
  4. // 记录链表总长度
  5. private int count = 0;
  6. // 赋值数组时记录索引
  7. private int index = 0;
  8. public int[] reversePrint(ListNode head) {
  9. recursion(head);
  10. return res;
  11. }
  12. public void recursion(ListNode head) {
  13. if (head != null) {
  14. count ++;
  15. recursion(head.next);
  16. res[index ++] = head.val;
  17. } else {
  18. res = new int[count];
  19. }
  20. }
  21. }

使用辅助栈

执行用时:2 ms, 在所有 Java 提交中击败了38.48% 的用户 内存消耗:38.9 MB, 在所有 Java 提交中击败了77.98% 的用户

  1. class Solution {
  2. public int[] reversePrint(ListNode head) {
  3. Stack<Integer> stack = new Stack<>();
  4. while (head != null) {
  5. stack.add(head.val);
  6. head = head.next;
  7. }
  8. int[] res = new int[stack.size()];
  9. for (int i = 0; i < res.length; i++) {
  10. res[i] = stack.pop();
  11. }
  12. return res;
  13. }
  14. }