Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
merge two sorted lists那道题的升级版。这道题标签里有heap,下次写考虑一下heap的方法。
Source
/**
* 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(List<ListNode> lists) {
if(lists.size() == 0) return null;
return sort(lists, 0, lists.size() - 1);
}
public ListNode sort(List<ListNode> lists, int low, int high){
if(low < high){
int mid = low + ((high - low) >> 1);
ListNode l1 = sort(lists, low, mid);
ListNode l2 = sort(lists, mid + 1, high);
return merge(l1, l2);
}
return lists.get(low);
}
public ListNode merge(ListNode l1, ListNode l2){
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode p1 = l1, p2 = l2, l3 = null, r = null;
if(p1.val < p2.val){
l3 = p1;
p1 = p1.next;
}
else{
l3 = p2;
p2 = p2.next;
}
r = l3;
while(p1 != null && p2 != null){
if(p1.val > p2.val){
l3.next = p2;
p2 = p2.next;
l3 = l3.next;
}
else{
l3.next = p1;
p1 = p1.next;
l3 = l3.next;
}
}
if(p2 != null){
l3.next = p2;
}
if(p1 != null){
l3.next = p1;
}
return r;
}
}
Test
public static void main(String[] args){
ListNode a = new ListNode(1);
List<ListNode> list = new ArrayList<ListNode>();
list.add(a);
a = new ListNode(0);
list.add(a);
ListNode list2 = new Solution().mergeKLists(list), p = list2;
while(p != null){
System.out.println(p.val);
p = p.next;
}
}