class Solution {
public ListNode mergeKLists(ListNode[] lists) {
int n = lists.length;
if (n == 0) {
return null;
}
ListNode head = lists[0];
for (int i = 1; i < lists.length; i++) {
head = merge(head, lists[i]);
}
return head;
}
private ListNode merge(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode root = new ListNode(), tail = root, tmp;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
tmp = l1;
l1 = l1.next;
} else {
tmp = l2;
l2 = l2.next;
}
tmp.next = null;
tail.next = tmp;
tail = tmp;
}
if (l1 != null) {
tail.next = l1;
}
if (l2 != null) {
tail.next = l2;
}
return root.next;
}
}
02-25
671
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-19
859
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-07
232
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-10
162
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-14
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交