题解 | #合并k个已排序的链表#
合并k个已排序的链表
http://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
return mergeList(lists,0,lists.size()-1);
}
public ListNode mergeList(List<ListNode> lists,int left,int right){
if(left == right){
return lists.get(left);
}
if(left > right){
return null;
}
int mid = left + (right - left)/2;
return merge(mergeList(lists,left,mid),mergeList(lists,mid+1,right));
}
public ListNode merge(ListNode l1,ListNode l2){
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode head = new ListNode(-1);
ListNode node = head;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
node.next = l1;
l1 = l1.next;
}else{
node.next = l2;
l2 = l2.next;
}
node = node.next;
}
if(l1 != null){
node.next = l1;
}else{
node.next = l2;
}
return head.next;
}
}