#include <iostream>
#include <vector>
#include "leetcode.h"
using namespace std;
class Solution {
public:
void sort(vector<ListNode*>& lists) {
ushort i = 0, length = lists.size();
for (ushort ii = 0; ii < length; ++ii) {
if (lists.at(ii) == nullptr)
continue;
if (lists.at(i) == nullptr || lists.at(i)->val > lists.at(ii)->val)
i = ii;
}
ListNode* temp = lists.at(i);
lists.at(i) = lists.at(0);
lists.at(0) = temp;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.size() == 0)
return nullptr;
sort(lists);
ListNode* ans = lists.front();
ListNode* begin, * end, * temp;
// 如果要归并的链到达尾节点,则跳出循环
bool flag = true;
for (int i = 1; i < lists.size(); ++i) {
begin = ans;
temp = lists.at(i);
// 如果该链为空直接跳过
if (!temp) continue;
if (nullptr == begin) { ans = temp; continue; }
while (flag) {
// 循环找出适合ans链接到temp的node
while (begin->next && begin->next->val < temp->val) {
begin = begin->next;
}
// 留一个指针继续搜索ans找到适合temp链接ans的node
end = begin->next;
if (nullptr == end) {
begin->next = temp;
flag = false;
continue;
}
begin->next = temp;
ListNode* btemp = temp;
while (nullptr != temp && nullptr != end && temp->val <= end->val) {
btemp = temp;
temp = temp->next;
}
if (nullptr == temp)
flag = false;
btemp->next = end;
}
flag = true;
}
return ans;
}
};