题目描述
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
代码
public ListNode mergeTwoLists(ListNode l1,ListNode l2) {
if(l1==null&&l2==null){
return null;
}
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
ListNode merged;
if(l1.val>l2.val){
merged=l2;
l2=l2.next;
merged.next=mergeTwoLists(l1,l2);
}else{
merged=l1;
l1=l1.next;
merged.next=mergeTwoLists(l1,l2);
}
return merged;
}