Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public int val; 5 * public ListNode next; 6 * public ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode MergeKLists(ListNode[] lists) { 11 if (lists == null || lists.Length == 0) return null; 12 13 return Sort(lists, 0, lists.Length - 1); 14 } 15 16 private ListNode Sort(ListNode[] lists, int start, int end) 17 { 18 if (start > end) 19 { 20 return null; 21 } 22 23 if (start == end) 24 { 25 return lists[start]; 26 } 27 28 int mid = start + (end - start) / 2; 29 var l1 = Sort(lists, start, mid); 30 var l2 = Sort(lists, mid + 1, end); 31 32 return Merge(l1, l2); 33 } 34 35 private ListNode Merge(ListNode l1, ListNode l2) 36 { 37 ListNode head = new ListNode(1), cur = head; 38 39 while (l1 != null || l2 != null) 40 { 41 if (l1 != null && l2 != null) 42 { 43 if (l1.val <= l2.val) 44 { 45 cur.next = l1; 46 l1 = l1.next; 47 } 48 else 49 { 50 cur.next = l2; 51 l2 = l2.next; 52 } 53 } 54 else if (l1 != null) 55 { 56 cur.next = l1; 57 l1 = l1.next; 58 } 59 else 60 { 61 cur.next = l2; 62 l2 = l2.next; 63 } 64 65 cur = cur.next; 66 } 67 68 return head.next; 69 } 70 }