题目大意:将K个升序的链表整合成一个
分析:链表、堆、分治归并的考察。最简单的方法就是取出K个链表中的最小值加入答案,最小值用堆(优先级队列)来维护。cmp函数讲解参考https://blog.csdn.net/ly59782/article/details/53161358。
第二种方法就是分治的思想,利用leetcode21里面的代码,两两不断合并,最终成为一个链表。
代码:
方法一:堆。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
struct cmp{
bool operator() (ListNode* a,ListNode* b){
return a->val > b->val;
}
};
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*,vector<ListNode*>,cmp> que;
for(int i = 0;i < lists.size();i++){
if(lists[i]) que.push(lists[i]);
}
ListNode* dummy = new ListNode(0);
ListNode* p = dummy;
while(!que.empty()){
ListNode* front = que.top();
que.pop();
p->next = front;
p = p->next;
if(front->next) que.push(front->next);
}
return dummy->next;
}
};
方法二:分治。转载自https://www.cnblogs.com/wangxiaobao/p/5768952.html
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dummy(0);
ListNode* head = &dummy;
while (l1 != nullptr && l2 != nullptr) {
if (l1 -> val < l2 -> val) {
head -> next = l1;
l1 = l1 -> next;
}
else {
head -> next = l2;
l2 = l2 -> next;
}
head = head -> next;
}
if (l1 != nullptr) {
head -> next = l1;
}
if (l2 != nullptr) {
head -> next = l2;
}
return dummy.next;
}
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.size() == 0) {
return nullptr;
}
ListNode dummy(0);
ListNode* head = &dummy;
head -> next = lists[0];
for (int i = 1; i < lists.size(); ++i) {
head -> next = mergeTwoLists(head->next, lists[i]);
}
return dummy.next;
}
};