先找递归终止的界限 ,找终止界限的前一个情况,找出联系(即递推公式)
- 递归终止的界限 要么 l1 为空l,要么 l2 为空
- 找终止界限的前一个情况,、
l1 --> null
l2 -->null - 联系就是
l1.next = mergeTwoLists(l1.next,l2);
or
l2.next = mergeTwoLists(l1,l2.next);
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
/** 终止界限,要么 l1 为空l,要么 l2 为空了*/
if (l1 == null) return l2;
if (l2 == null) return l1;
/** 问题与子问题间的关系即递推公式,
* 如果 l1 < l2 ,那么就 l1 指向下一个,如果 l1 >= l2 ,那么就 l2 指向下一个*/
if (l1.val < l2.val){
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}else {
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
}