import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类ArrayList
* @return ListNode类
*/
public ListNode mergeKLists (ArrayList<ListNode> lists) {
// write code here
if(lists==null || lists.size()==0){
return null;
}
if(lists.size()==1){
return lists.get(0);
}
//合并两个
ListNode n1=lists.get(0);
ListNode n2=lists.get(1);
ListNode result=merge(n1,n2);
for(int i=2;i<lists.size();i++){
result=merge(result,lists.get(i));
}
return result;
}
private ListNode merge(ListNode n1, ListNode n2){
if(n1==null|| n2==null){
return n1!=null?n1:n2;
}
if(n1.val<=n2.val){
n1.next=merge(n1.next,n2);
return n1;
}else{
n2.next=merge(n2.next,n1);
return n2;
}
}
}