解题思路:
1 之前的某道题有将两个有序链表排序的解法,思路很简单,可以拿来直接用。
2 利用分治的思想,分根据下标来分;两两合并,再两两合并…以此类推。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public static ListNode mergeKLists(ListNode[] lists){
return partion(lists,0,lists.length-1);
}
public static ListNode partion(ListNode[] lists,int s,int e){
if(s==e) return lists[s];
if(s<e){
int q=(s+e)/2;
ListNode l1=partion(lists,s,q);
ListNode l2=partion(lists,q+1,e);
return mergeTwoLists(l1,l2);
}else
return null;
}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode p = l1;
ListNode q = l2;
ListNode result;
ListNode r;
if (l1 == null)
return l2;
if (l2 == null)
return l1;
if (p.val <= q.val){
result = new ListNode(p.val);
r = result;
p = p.next;
}
else{
result = new ListNode(q.val);
r = result;
q = q.next;
}
while (p != null && q != null){
while (p != null && q != null && p.val <= q.val){
r.next = p;
r = r.next;
p = p.next;
}
while (p != null && q != null && q.val <= p.val){
r.next = q;
r = r.next;
q = q.next;
}
}
if (q == null)
r.next = p;
else r.next = q;
return result;
}
}