参考:
https://leetcode.com/problems/merge-k-sorted-lists/discuss/10527/Difference-between-Priority-Queue-and-Heap-and-C%2B%2B-implementation (评论里的新加一个节点的那个)
- 优先队列方法:
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, compare> q;
for (auto l : lists) {
if (l) {
q.push(l); //每个链表取一个元素放入优先队列
}
}
ListNode pre(0); //新建一个头结点,可以防止丢失最终链表的头
ListNode *node = ⪯
while (q.size()) {
ListNode *top = q.top(); //从优先队列里取最小的那个元素
q.pop();
node->next = top; //将弹出的那个元素连到最终链表上
node = node->next; //指针向后移一步
if (top->next) {
q.push(top->next); //将下一个元素入队列
}
}
return pre.next;
}
struct compare {
bool operator()(const ListNode* l1, const ListNode* l2) {
return l1->val > l2->val;
}
};
};
- 归并排序方法
参考:
https://leetcode.com/problems/merge-k-sorted-lists/discuss/10882/C%2B%2B-solution-using-Merge-Sort
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
return partition(lists, 0, lists.size()-1); //合并0-(size-1)的链表
}
ListNode* partition(vector<ListNode*>& lists, int start, int end){
if(start == end){
return lists[start];
}
if(start < end){
int mid = (end+start)/2;
ListNode* l1 = partition(lists, start, mid); //合并start->mid的链表
ListNode* l2 = partition(lists, mid+1, end); //合并mid+1到end的链表
//partition最终递归到最后还是两个链表的合并.举个例子来说比如合并6个链表,那么按照分治法,我们首先分别合并1和4,2和5,3和6。这样下一次只需合并3个链表,我们再合并1和3,最后和2合并就可以了。
return merge(l1, l2);
}
return NULL;
}
ListNode* merge(ListNode* l1, ListNode* l2){ //合并L1,L2两个有序链表
if(!l1) return l2;
if(!l2) return l1;
if(l1->val < l2->val){
l1->next = merge(l1->next, l2);
return l1;
}else{
l2->next = merge(l1, l2->next);
return l2;
}
}
};