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;
    }
posted @ 2020-04-26 09:31  ~吹梦到西洲~  阅读(169)  评论(0编辑  收藏  举报