给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
示例 2:
输入:lists = []
输出:[]
示例 3:
输入:lists = [[]]
输出:[]
code
优先队列:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
struct Node
{
int val;
ListNode* ptr;
bool operator < (const Node& a) const{
return val > a.val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<Node>q;
ListNode head,*tail = &head;
for(ListNode* list : lists)
{
if(list)
{
q.push({list->val,list});
}
}
while(!q.empty())
{
auto t = q.top();q.pop();
tail->next = t.ptr;
tail = tail->next;
if((t.ptr)->next)
{
q.push({(t.ptr)->next->val,(t.ptr)->next});
}
}
return head.next;
}
};
归并:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
void print(ListNode* a)
{
while(a)
{
cout<<a->val<<" ";
a = a->next;
}
cout<<endl;
}
ListNode* mergeTwoList(ListNode* a,ListNode* b)
{
if(!a || !b) return a ? a:b;
ListNode head;
ListNode* tail = &head;
while(a && b)
{
if(a->val <= b->val)
{
tail->next = a;
a = a->next;
}
else
{
tail->next = b;
b = b->next;
}
tail = tail->next;
}
tail->next = a ? a:b;
return head.next;
}
ListNode* merge(vector<ListNode*>& lists,int l,int r)
{
if(l == r) return lists[l];
if(l>r) return NULL;
int mid = (l + r)/2;
return mergeTwoList(merge(lists,l,mid),merge(lists,mid+1,r));
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
return merge(lists,0,lists.size()-1);
}
};