题解 | #牛群的合并#
牛群的合并
https://www.nowcoder.com/practice/d0cb24e1494e4f45a4b7d1a17db0daef
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类一维数组
* @return ListNode类
*/
public ListNode mergeKLists (ListNode[] lists) {
if(lists.length==0){
return null;
}else if (lists.length==1){
return lists[0];
}
ListNode headNode = lists[0];
// write code here
for(int i =1 ; i<lists.length;i++){
headNode = mergeTwoLists(headNode,lists[i]);
}
return headNode;
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
} else if (l2 == null) {
return l1;
} else if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}