题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <list>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类vector
* @return ListNode类
*/
ListNode* mergeKLists(vector<ListNode*>& lists) {
// write code here
if (lists.empty()) {
return nullptr;
}
if (lists.size() < 2) {
return lists[0];
}
std::list<ListNode*> l;
for (auto p : lists) {
l.push_back(p);
}
while (l.size() > 1) {
ListNode* p1 = l.front();
l.pop_front();
ListNode* p2 = l.front();
l.pop_front();
l.push_back(Merge2(p1, p2));
}
return l.front();
}
private:
ListNode* Merge2(ListNode* p1, ListNode* p2) {
if (!p1) {
return p2;
}
if (!p2) {
return p1;
}
auto* pre = new ListNode(-1);
auto* new_head = pre;
pre->next = p1;
while (p1 && p2) {
if (p1->val < p2->val) {
pre->next = p1;
p1 = p1->next;
} else {
pre->next = p2;
p2 = p2->next;
}
pre = pre->next;
}
if (p1) {
pre->next = p1;
}
if (p2) {
pre->next = p2;
}
return new_head->next;
}
};

