AC:
package 链表;
import java.util.List;
public class 合并k个升序链表 {
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public ListNode merge(ListNode[] lists,int l,int r){
if(l==r){
return lists[l];
}
if(l>r){
return null;
}
int mid=(l+r)>>1;
return mergeKListtow(merge(lists,l,mid),(merge(lists,mid+1,r)));
}
public ListNode mergeKLists(ListNode[] lists) {
return merge(lists,0,lists.length-1);
}
public ListNode mergeKListtow(ListNode a,ListNode b) {
if(a==null||b==null){
return a==null?b:a;
}
ListNode head=new ListNode(0);
ListNode aptr=a,bptr=b;
ListNode tail=head;
while (aptr!=null&&bptr!=null){
if(aptr.val>bptr.val){
tail.next=bptr;
bptr=bptr.next;
}else {
tail.next=aptr;
aptr=aptr.next;
}
tail=tail.next;
}
tail.next=(aptr==null?bptr:aptr);
return head.next;
}
}