合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
#include <iostream>
#include <windows.h>
#include <vector>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
int getMin(vector<ListNode*> lists) {
int j = 0;
for (j = 0; j < lists.size(); j++)
if (lists[j])
break;
int nowVal = lists[j]->val;
int index = j;
for (int i = 0; i < lists.size(); i++) {
if (lists[i] && lists[i]->val < nowVal) {
nowVal = lists[i]->val;
index = i;
}
}
return index;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode result(0);
ListNode* endPtr = &result;
int listCount = 0;
for (ListNode* p : lists) {
if (p)
listCount++;
}
while (listCount > 0) {
int index = getMin(lists);
ListNode* temp = lists[index]->next;
lists[index]->next = endPtr->next;
endPtr->next = lists[index];
endPtr = lists[index];
lists[index] = temp;
if (!lists[index])
listCount--;
}
return result.next;
}
int main() {
ListNode a1(1);
ListNode a2(4);
ListNode a3(5);
ListNode b1(1);
ListNode b2(3);
ListNode b3(4);
ListNode c1(2);
ListNode c2(6);
a1.next = &a2;
a2.next = &a3;
b1.next = &b2;
b2.next = &b3;
c1.next = &c2;
vector<ListNode*> lists = { &a1, &b1, &c1 };
ListNode* result = mergeKLists(lists);
ListNode* p = result;
while (p) {
cout << p->val << " ";
p = p->next;
}
cout << endl;
system("pause");
return 0;
}