创建一个新的向量,按顺序将每个牛群中的节点放入向量中,然后使用sort函数按照升序进行排序,最后将向量中的节点合并成新的链表返回。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <iterator>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类vector
* @return ListNode类
*/
ListNode* mergeKLists(vector<ListNode*>& lists) {
// write code here
vector<ListNode*> list;
ListNode* current;
ListNode* result;
for(vector<ListNode*>::iterator it = lists.begin(); it != lists.end(); it++) {
current = *it;
while(current != nullptr) {
list.push_back(current);
current = current->next;
}
}
if(list.size() == 0) {
return nullptr;
}
sort(list.begin(), list.end(), compare);
for(int i = 0; i < list.size(); i++) {
if(i == 0) {
result = list.at(i);
current = result;
} else {
current->next = list.at(i);
current = current->next;
if(i == list.size() - 1) {
current->next = nullptr;
}
}
}
return result;
}
static bool compare(ListNode* a, ListNode* b) {
return a->val < b->val;
}
};



京公网安备 11010502036488号