Ideas:
It is equivalent to multiple operations of merging 2 ascending linked lists, simplifying k to 2
Is actually using the divide and conquer method
Merge 2 ascending linked lists to view ( https://blog.csdn.net/di_ko/article/details/115062966 )
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists==null||lists.length==0) return null;
return merge(lists,0,lists.length-1);
}
private ListNode merge(ListNode[] lists,int low,int high){
if(low==high) return lists[low];
if(low>high) return null;
int mid=low+(high-low)/2;
return mergeTwoLists(merge(lists,low,mid),merge(lists,mid+1,high));
}
private ListNode mergeTwoLists(ListNode a, ListNode b) {
if(a==null||b==null){
return a==null?b:a;
}
//注意空链表的new形式
ListNode head=new ListNode(0);
ListNode tail=head;//是与head一致,而不是重新new一个
ListNode aPtr=a,bPtr=b;
//以下所有都是写aPtr或bPtr,而不是a或b
while(aPtr!=null&&bPtr!=null){
if(aPtr.val<bPtr.val){
tail.next=aPtr;
aPtr=aPtr.next;
}else{
tail.next=bPtr;
bPtr=bPtr.next;
}
tail=tail.next;
}
tail.next=aPtr==null?bPtr:aPtr;
//返回的是head.next,而不是head
return head.next;
}
}
break down:
Deal with the use of divide and conquer method, you can also violently, merge 2 linked lists in sequence
ListNode res=null;
for(int i=0;i<lists.length;i++){
res=mergeTwoLists(res,lists[i]);
}