7.12 能自己 A 出来

题目描述


原题链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

  1. 输入:head = [1,3,2]
  2. 输出:[2,3,1]

解题思路:递归回溯


K神题解:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/

递归回溯的方法体怎么写:

  • 最开始写的是递归的终止条件,然后返回 return 即可。
  • 接下来就是递归体现:调用递归方法
  • 最后就是回溯时要干什么

递归回溯 递归回溯,先递归再回溯,但最开始要写上递归的终止条件。

  1. // 把ArrayList 放外面,递归方法才可以使用
  2. List<Integer> tmp = new ArrayList<>();
  3. public int[] reversePrint(ListNode head) {
  4. // 注意是放 head 不是 head.next
  5. recur(head);
  6. int[] res = new int[tmp.size()];
  7. for(int i = 0; i < res.length; i++) {
  8. res[i] = tmp.get(i);
  9. }
  10. return res;
  11. }
  12. public void recur(ListNode head) {
  13. if(head == null) return;
  14. recur(head.next);
  15. tmp.add(head.val);
  16. }