Merges a K-linked list.
Idea: Merge the list 22 first until you merge it into only one linked list
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* mergeklists (vector<listnode*>&lists) { A if(Lists.empty ())returnNULL; - intLen =lists.size (); - while(len>1){ the for(intI=0; i<len/2; i++){ -Lists[i] = mergetwolists (lists[i],lists[len-1-i]); - } -Len = (len+1)/2; This technique is very useful . + } - returnLists.front (); + } Alistnode* mergetwolists (listnode*l1,listnode*L2) { at if(NULL==L1)returnL2; - Else if(NULL==L2)returnL1; - if(l1->val<l2->val) { -L1->next = Mergetwolists (l1->next,l2); - returnL1; - } in Else { -L2->next = Mergetwolists (l1,l2->next); to returnL2; + } - } the};
"Leetcode" 23. Merge k Sorted Lists