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 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
class Solution { public ListNode mergeKLists(ListNode[] lists) { if (lists.length == 0) return null; return split(lists, 0, lists.length - 1); }
public ListNode split(ListNode[] lists, int i, int j) { if (i == j) return lists[i]; int m = (i + j) >>> 1; ListNode left = split(lists, i, m); ListNode right = split(lists, m + 1, j); return mergeTwoLists(left, right); }
public ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode dummy = new ListNode(0); ListNode current = dummy; while (list1 != null && list2 != null) { if (list1.val < list2.val) { current.next = list1; list1 = list1.next; } else { current.next = list2; list2 = list2.next; } current = current.next; } if (list1 == null) { current.next = list2; return dummy.next; } if (list2 == null) { current.next = list1; return dummy.next; } return dummy.next; } }
|