题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include<algorithm> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类vector * @return ListNode类 */ #include<algorithm> static bool compare(int a,int b) { return a<b; //升序排列 } ListNode* mergeKLists(vector<ListNode*>& lists) { // write code here vector<int> result; int sum=lists.size(); ListNode *next=NULL; if(lists.empty()) return NULL; for(int i=0;i<sum;i++) { while(lists[i]!=NULL) { next=lists[i]->next; result.push_back(lists[i]->val); lists[i]=next; } } if(result.empty()) return NULL; std::sort(result.begin(),result.end(),compare); ListNode *head=new ListNode(result[0]); head->next=NULL; ListNode *last=head; for(int i=1;i<result.size();i++) { ListNode *tmp=new ListNode(result[i]); last->next=tmp; tmp->next=NULL; last=tmp; } return head; } };