23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
利用mergeTwoSortedLists的结果
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty()) return nullptr;
while(lists.size() >1){
lists.push_back(mergeTwoSortedLists(lists[0], lists[1]));
lists.erase(lists.begin());
lists.erase(lists.begin());
}
return lists.front();
}
ListNode* mergeTwoSortedLists(ListNode *l1, ListNode *l2){
if(l1 == nullptr) return l2;
if(l2 == nullptr) return l1;
if(l1->val < l2->val){
l1->next = mergeTwoSortedLists(l1->next, l2);
return l1;
}else{
l2->next = mergeTwoSortedLists(l1, l2->next);
return l2;
}
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct cmp{
bool operator() (const ListNode *a, const ListNode *b){
return a->val > b->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode *, vector<ListNode *>, cmp> pq;
//注意此处要判断是否为nullptr,再加入队列中,nullptr也可以加入队列中
for(auto &l:lists)
if(l)
pq.push(l);
if(pq.empty()) return nullptr;
ListNode *head = pq.top();
pq.pop();
if(head->next) pq.push(head->next);
ListNode *tail = head;
while(!pq.empty()){
tail->next = pq.top();
pq.pop();
tail = tail->next;
if(tail->next) pq.push(tail->next);
}
return head;
}
};
测试用例
[[1, 2, 3], [4, 5, 6],[7, 8, 9],[0, 10]]