合并 k 个排序链表,返回合并后的排序链表。
public class MergeKSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length == 0)return null;
if(lists.length == 1)return lists[0];
int i = 1;
int n = lists.length;
while (i<n) {
//拿lists[0]和lists[i]合并,放入lists[0]
ListNode head = null;
ListNode tmp = head;
while (lists[0]!=null && lists[i]!=null) {
if(lists[0].val<lists[i].val) {
if(tmp == null) {
head = new ListNode(lists[0].val);
tmp = head;
}else {
tmp.next = lists[0];
tmp = tmp.next;
}
lists[0] = lists[0].next;
}else {
if(tmp == null) {
head = new ListNode(lists[i].val);
tmp = head;
}else {
tmp.next = lists[i];
tmp = tmp.next;
}
lists[i] = lists[i].next;
}
}
if(lists[0]!=null) {
if(tmp == null) {
tmp = lists[0];
head = tmp;
}
else {
tmp.next = lists[0];
}
}
if(lists[i]!=null) {
if(tmp == null) {
tmp = lists[i];
head = tmp;
}
else {
tmp.next = lists[i];
}
}
lists[0] = null;
lists[0] = head;
i++;
}
return lists[0];
}
}