Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6直接复用归并排序即可
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { ListNode *res=NULL; for(int i=0;i<lists.size();++i) { if(NULL==res) { res=lists[i]; continue; } res=merge(res,lists[i]); } return res; } ListNode* merge(ListNode *l1,ListNode *l2) { if(NULL==l1)return l2; if(NULL==l2)return l1; if(l1->val<l2->val) { l1->next=merge(l1->next,l2); return l1; } l2->next=merge(l1,l2->next); return l2; } };