思路:比较两个列表首节点,按照大小合成一个新链表,如果一个链表为空,则把另外的链表直接合入新链表。(递归)
public ListNode mergeTwoList(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode mergeHead;
if (l1.val < l2.val) {
mergeHead = l1;
mergeHead.next = mergeTwoList(l1.next,l2);
}
else {
mergeHead = l2;
mergeHead.next = mergeTwoList(l1, l2.next);
}
return mergeHead;
}