两条和n条的合并并没有什么太大的差距
import java.util.*;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
ListNode res = null;
public ListNode mergeKLists(ArrayList<ListNode> lists) {
if (lists.size() == 0) {
return res;
}
res = lists.get(0);
for (int i = 1; i < lists.size(); i++) {
merge(res, lists.get(i));
}
return res;
}
private void merge(ListNode a, ListNode b) {
ListNode head = new ListNode(-1);
ListNode cur = head;
while (a != null && b != null) {
if (a.val < b.val) {
cur.next = a;
a = a.next;
cur = cur.next;
} else {
cur.next = b;
b = b.next;
cur = cur.next;
}
}
while (a != null) {
cur.next = a;
a = a.next;
cur = cur.next;
}
while (b != null) {
cur.next = b;
b = b.next;
cur = cur.next;
}
res = head.next;
}
}
京公网安备 11010502036488号