注意lists为空时,归并时会l<r,导致一直递归。。栈溢出
class Solution {
public ListNode[] lists;
public ListNode mergeTwo(ListNode l1,ListNode l2){
ListNode head=new ListNode();
ListNode now=head;
while(l1!=null&&l2!=null){
if(l1.val<l2.val){now.next=l1;now=now.next;l1=l1.next;}
else{now.next=l2;now=now.next;l2=l2.next;}
}
while(l1!=null) {now.next=l1;now=now.next;l1=l1.next;}
while(l2!=null) {now.next=l2;now=now.next;l2=l2.next;}
return head.next;
}
public ListNode merge(int l,int r){
if(l>r) return null;//防止lists为空
if(l==r) return lists[l-1];
int mid=(l+r)>>1;
return mergeTwo(merge(l,mid),merge(mid+1,r));
}
public ListNode mergeKLists(ListNode[] lists) {
this.lists=lists;
return merge(1,lists.length);
}
}