问题
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
说明
根据问题21LeetCode算法21:java 合并两个有序链表结合,进行两两合并,问题迎刃而解。
代码
import Utils.ListNode;
import Utils.delwithListNode;
public class _23MergekSortedLists{
public ListNode mergeKLists(ListNode[] lists){
ListNode result = null;
for (int i=0; i<lists.length; i++) {
result = mergeTwoLists(result,lists[i]);
}
return result;
}
public ListNode mergeTwoLists(ListNode L1,ListNode L2){
ListNode head = null;
ListNode tmp = null;
while(L1!=null||L2!=null){
if(L1!=null&&L2!=null){
if(L1.val>=L2.val){
if(tmp==null){
tmp = L2;
head = tmp;
L2 = L2.next;
}else{
tmp.next = L2;
tmp = tmp.next;
L2 = L2.next;
}
}else{
if(tmp==null){
tmp = L1;
head = tmp;
L1 = L1.next;
}else{
tmp.next = L1;
tmp = tmp.next;
L1 = L1.next;
}
}
}else if(L1!=null&&L2==null){
if(tmp==null){
tmp = L1;
head = tmp;
return head;
}else{
tmp.next = L1;
return head;
}
}else{
if(tmp==null){
tmp = L2;
head = tmp;
return head;
}else{
tmp.next = L2;
return head;
}
}
}
return head;
}
public static void main(String[] arg){
ListNode[] lists = new ListNode[3];
ListNode L1 = delwithListNode.getNodelist(new int[]{1,4,5});
ListNode L2 = delwithListNode.getNodelist(new int[]{1,3,4});
ListNode L3 = delwithListNode.getNodelist(new int[]{2,6});
lists[0] = L1;
lists[1] = L2;
lists[2] = L3;
_23MergekSortedLists MergekSortedLists = new _23MergekSortedLists();
ListNode result = MergekSortedLists.mergeKLists(lists);
String list = delwithListNode.readList(result);
System.out.println(list);
}
}
其中
import Utils.ListNode;
import Utils.delwithListNode;