k个有序链表有序合并
本题我使用优先队列进行解决,每次拿出一个最小的元素即可,注意在push元素时,检查链表指针是否为空:
struct Ele
{
int val;
ListNode *ptr;
bool operator < (const Ele &r) const
{
return val > r.val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists)
{
priority_queue <Ele> q;
for (int i = 0;i<lists.size();++i)
{
if (lists[i]!=NULL)
q.push({lists[i]->val, lists[i]});
}
ListNode head, *p = &head;
while (!q.empty())
{
Ele f = q.top();
q.pop();
p->next = f.ptr;
p = p->next;
if (f.ptr->next)
q.push({f.ptr->next->val, f.ptr->next});
}
return head.next;
}

浙公网安备 33010602011771号