public static ListNode mergeKLists(ListNode[] lists){
return partion(lists,0,lists.length-1);
}
//将k个lists分解成两两合并
public static ListNode partion(ListNode[] lists,int s,int e){
if(s==e) return lists[s];
if(s<e){
int q=(s+e)/2;
ListNode l1=partion(lists,s,q);
ListNode l2=partion(lists,q+1,e);
return merge(l1,l2);
}else
return null;
}
//This function is from Merge Two Sorted Lists.
public static ListNode merge(ListNode l1,ListNode l2){
if(l1==null) return l2;
if(l2==null) return l1;
if(l1.val<l2.val){
l1.next=merge(l1.next,l2);//合并的递归
return l1;
}else{
l2.next=merge(l1,l2.next);
return l2;
}
}
java递归
最新推荐文章于 2024-01-09 20:31:27 发布