套用归并排序的思想,要排序这k个链表,先排序好前k/2个链表,再排序好后k/2个链表,最后将这两个链表用普通的两链表合并就能解决问题
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0)
return null;
return mergeKLists(lists, 0, lists.length - 1);
}
private ListNode mergeKLists(ListNode[] lists, int left, int right) {
if (left == right) {
return lists[left];
} else {
int mid = (right - left) / 2 + left;
ListNode list1 = mergeKLists(lists, left, mid);
ListNode list2 = mergeKLists(lists, mid + 1, right);
return merge2Lists(list1, list2);
}
}
private ListNode merge2Lists(ListNode list1, ListNode list2) {
ListNode dymmyHead = new ListNode(0, null);
ListNode cur=dymmyHead;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
cur.next = list1;
list1 = list1.next;
} else {
cur.next=list2;
list2 = list2.next;
}
cur=cur.next;
}
while (list1 != null) {
cur.next=list1;
list1=list1.next;
cur=cur.next;
}
while (list2 != null) {
cur.next=list2;
list2 = list2.next;
cur = cur.next;
}
return dymmyHead.next;
}
}