合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
思路
先合并两条链表,以此类推,合并k - 1次
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
ListNode mergeList = lists[0];
for (int i = 1; i < lists.length; i++) {
mergeList = merge(mergeList, lists[i]);
}
return mergeList;
}
//合并两条有序链表
public static ListNode merge(ListNode list1, ListNode list2) {
ListNode dumy = new ListNode(0);
ListNode temp = dumy;
while (list1 != null && list2 != null) {
ListNode node;
if (list1.val < list2.val) {
node = new ListNode(list1.val);
list1 = list1.next;
} else {
node = new ListNode(list2.val);
list2 = list2.next;
}
temp.next = node;
temp = temp.next;
}
temp.next = (list1 == null) ? list2 : list1;
// while (list1 != null) {
// ListNode node = new ListNode(list1.val);
// temp.next = node;
// temp = temp.next;
// list1 = list1.next;
// }
// while (list2 != null) {
// ListNode node = new ListNode(list2.val);
// temp.next = node;
// temp = temp.next;
// list2 = list2.next;
// }
return dumy.next;
}
}