1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
class Solution { public ListNode mergeKLists(ListNode[] lists) { return merge(lists, 0, lists.length - 1); }
private ListNode merge(ListNode[] lists, int l, int r) { if (l == r) return lists[l]; else if (l > r) return null; int mid = l + r >> 1; ListNode p1 = merge(lists, l, mid); ListNode p2 = merge(lists, mid + 1, r); return mergeTwoList(p1, p2); }
private ListNode mergeTwoList(ListNode p1, ListNode p2) { if (p1 == null) return p2; else if (p2 == null) return p1; if (p1.val < p2.val) { p1.next = mergeTwoList(p1.next, p2); return p1; } else { p2.next = mergeTwoList(p1, p2.next); return p2; } } }
|