21. 合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
/**
* 普通解法
* @param l1
* @param l2
* @return
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode headPre = new ListNode();
if (l1 == null && l2 == null) return null;
ListNode res = headPre;
ListNode p1 = l1;
ListNode p2 = l2;
while(p1 != null && p2 != null){
if (p1.val < p2.val){
res.next = new ListNode();
res = res.next;
res.val = p1.val;
p1 = p1.next;
}else {
res.next = new ListNode();
res = res.next;
res.val = p2.val;
p2 = p2.next;
}
}
if (p2 != null){
while (p2 != null){
res.next = new ListNode();
res = res.next;
res.val = p2.val;
p2 = p2.next;
}
}
if (p1 != null){
while(p1 != null){
res.next = new ListNode();
res = res.next;
res.val = p1.val;
p1 = p1.next;
}
}
return headPre.next;
}
/**
* 递归解法
* @param l1
* @param l2
* @return
*/
public static ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
if (l1 == null){
return l2;
}
if (l2 == null){
return l1;
}
if (l1.val < l2.val){
l1.next = mergeTwoLists2(l1.next,l2);
return l1;
}else {
l2.next = mergeTwoLists2(l1,l2.next);
return l2;
}
}