# leetcode 23. Merge k Sorted Lists and 21. Merge Two Sorted Lists

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 mergeKLists(ListNode[] lists) {
if(lists==null||lists.length==0) return null;
return merge(lists,0,lists.length-1);
}
public ListNode merge(ListNode[] lists,int start,int end){//合并start到end的节点
if(start==end) return lists[start];
ListNode listnode1=merge(lists,start,(start+end)/2);
ListNode listnode2=merge(lists,(start+end)/2+1,end);
//合并两个链表，定义练个节点之下listnode1和listnode2的当前结点
ListNode cur1=listnode1,cur2=listnode2,cur3=null;
while(true){
if(cur2==null){
if(cur3==null){
cur3=cur1;
}else{
cur3.next=cur1;
}
break;
}else if(cur1==null){
if(cur3==null){
cur3=cur2;
}else{
cur3.next=cur2;
}
break;
}
if(cur1.val<cur2.val){
if(cur3==null){
cur3=cur1;
}else{
cur3.next=cur1;
cur3=cur3.next;
}
cur1=cur1.next;
}else{
if(cur3==null){
cur3=cur2;
}else{
cur3.next=cur2;
cur3=cur3.next;
}
cur2=cur2.next;
}

}
}

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
ListNode cur1=l1,cur2=l2,cur3=null;
if(cur1.val>cur2.val){//初始情况
cur2=cur2.next;
}
else if(cur1.val<=cur2.val){
cur1=cur1.next;
}
while(true){
if(cur1==null){
cur3.next=cur2;
break;
}
if(cur2==null){
cur3.next=cur1;
break;
}
if(cur1.val<cur2.val){
cur3.next=cur1;
cur1=cur1.next;
}else{
cur3.next=cur2;
cur2=cur2.next;
}
cur3=cur3.next;
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120