剑指 Offer 06. 从尾到头打印链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
ArrayList<Integer> tmp = new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
recur(head);
int[] res = new int[tmp.size()];
for(int i = 0 ; i < res.length ; i++){
res[i] = tmp.get(i);
}
return res;
}
void recur(ListNode head){
if(head == null) return;
recur(head.next);
tmp.add(head.val);
}
}
总结
注意递归的形式:
递归函数中一般会包含三个部分:
- 基线条件(跳出条件)
- 递归条件
- 递归处理(递归函数要实现的功能)
这三个部分一般没有具体的顺序要求,但需要注意的是基线条件(跳出条件)必须在递归条件之前,否则递归函数会无限递归。
小技巧
当你需要使用数组但不确定数组的长度时,你可以使用ArrayList