点击打开链接
//多路归并 struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* head = new ListNode(0); ListNode* temp = head; while(l1 && l2){ if(l1->val < l2->val){ head->next = l1; head = head->next; l1 = l1->next; } else{ head->next = l2; head = head->next; l2 = l2->next; } } if(l1){ head-> next =l1; } else{ head->next = l2; } return temp->next; } ListNode* mergeKLists(vector<ListNode*>& lists) { int n = lists.size(); if(n==0) return NULL; while (n>1) { int k = (n+1) / 2; for(int i=0; i<n/2; i++){ lists[i] = mergeTwoLists(lists[i], lists[i+k]);//归并分开看 } n = k; } return lists[0]; } };