将两个有序链表合并为一个新的有序链表并返回。 新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
* 解题思路 * 遍历l1 l2 直到其中一个遍历完成 再将另一个未遍历的部分放到链表的末尾 * 注意( l1 和 l2是否为null ) 如果都为null 则返回 null * 如果其中一个为null 则返回另外一个
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1==null&&l2==null){
return null;
}else if (l1==null){
return l2;
}else if (l2==null){
return l1;
}
ListNode head = new ListNode(0);
if (l1.val<l2.val){
head.val = l1.val;
l1=l1.next;
}else {
head.val = l2.val;
l2=l2.next;
}
ListNode res =head;
while (l1!=null&&l2!=null){
if (l1.val<l2.val){
head.next = l1;
l1=l1.next;
head =head.next;
}else {
head.next = l2;
l2=l2.next;
head =head.next;
}
}
if (l1!=null){
head.next = l1;
}else if(l2!=null){
head.next = l2;
}
return res ;
}