Leetcode 23.合并k个有序链表

class Solution {
public:
    struct cmp
    {
       bool operator()(ListNode *a,ListNode *b)
       {
           return a->val>b->val;
       } 
    };
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode*,vector<ListNode*>,cmp> heap;
        ListNode* dummy=new ListNode(-1),*tail=dummy;
        for(auto l:lists)//将所有链表的头节点插入堆中
            if(l!=NULL)
                heap.push(l);
        while(heap.size())
        {
            auto t=heap.top();//取出指向最小元素的指针
            heap.pop();
            tail=tail->next=t;
            if(t->next)
                heap.push(t->next);//更新指针
        }
        return dummy->next;
    }
};

posted @ 2023-03-17 15:51  穿过雾的阴霾  阅读(12)  评论(0)    收藏  举报