题目:
算法思想 :因为两个链表是有序的,所以额外创建一个头结点,然后按照顺序依次把l1,l2的头结点插入到新的链表的尾部,注意最后需要额外判断一下,因为两个链表不一定是同时结束的
代码:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}
else if(l2 == null){
return l1;
}
ListNode head = new ListNode(-1);
ListNode cur = head;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
cur.next = l1;
l1 = l1.next;
}
else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if(l1 != null){
cur.next = l1;
}
else{
cur.next = l2;
}
return head.next;
}