Today's topic a little bit complicated, because it is a merger of K ordered lists, see this question after the general idea is this:
1. First, do first merge two lists, the merger of the list I am thinking of using recursive operation,
2. Followed by merging multiple linked list, so the first step towards the foundation, I consider each selection to merge two lists, a list array as a whole, then it can be combined using merge algorithm using two pointer pointing to the current location of the array, a pointer to continue until a slicing position, and back, and then combined, since the recursive operation, to ensure that there will only be two sorted lists each time combined.
So the key is to figure out how this car recursively to merge two lists, and how to incorporate a large array of recursive
Here is the code:
1 package algorithm; 2 3 public class RecursiveSort { 4 5 public ListNode mergeKLists(ListNode[] lists) { 6 if(lists.length < 1){ 7 return null; 8 } 9 10 return merge(lists,0,lists.length-1); 11 } 12 13 private ListNode merge(ListNode[] lists,int left,int right){ 14 15 if(left >= right){ 16 return lists[left]; 17 } 18 int center = (left+right)/2; 19 20 ListNode leftNode = merge(lists,left,center); 21 ListNode rightNode = merge(lists,center+1,right); 22 23 ListNode temp = new ListNode(); 24 temp = mergeTwoListNode2(leftNode,rightNode,temp); 25 26 return temp; 27 28 } 29 30 /** 31 * 递归合并 32 * @paramL1 33 is * @param L2 34 is * @param TEMP 35 * @return 36 * / 37 [ Private ListNode mergeTwoListNode2 (ListNode L1, L2 ListNode, ListNode TEMP) { 38 is IF (L1 == null || L2 == null ) { 39 IF (L1 == null && L2 == null ) { 40 return L1; // borderline cases which are possible return 41 is } the else { 42 is TEMP L1 = == null ? l2 : l1; 43 } 44 45 return temp; 46 } 47 48 if(l1.val > l2.val){ 49 temp = l2; 50 temp.next = mergeTwoListNode2(l1,l2.next,temp.next); 51 }else { 52 temp = l1; 53 54 temp.next = mergeTwoListNode2(l1.next,l2,temp.next); 55 } 56 57 return temp; 58 59 } 60 61 }
Finally, tell the truth, for I did not thoroughly understand recursion, sleepwalk This question can be considered complete, but think the more important point is to make simple, that is, first merge two lists is resolved, that the remaining list of more merger can change this step is a merger of the two repeatedly linked list