合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
/* Definition for singly-linked list.*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
/*min-heap*/
struct Cmp {
bool operator () (ListNode *a, ListNode *b) {
return a->val > b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, Cmp> q;
auto iter = lists.begin();
for (; iter != lists.end(); iter++){
if (*iter != nullptr) {
q.push(*iter);
}
}
ListNode* head = nullptr;
ListNode* item = nullptr;
ListNode* prev = nullptr;
while(!q.empty()) {
item = q.top();
q.pop();
if (head == nullptr) {
head = item;
} else {
prev->next = item;
}
prev = item;
if (item->next != nullptr) {
q.push(item->next);
}
}
return head;
}
};