题目:力扣
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
#include<vector>
using std::vector;
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* res,*head;
head=new ListNode;
res=head;
if(lists.empty())
return head->next;
vector<int> temp;
//遍历链表数组
for(auto&&list:lists)
{
while(list!=nullptr)
{
temp.push_back(list->val);
list=list->next;
}
}
sort(temp.begin(),temp.end());
for(auto &&t:temp)
{
res->next=new ListNode(t);
res=res->next;
}
return head->next;
}
};
提交结果: