LeetCode 23. Merge k Sorted Lists

时间:2022-02-23 19:46:29

题目链接
n是总共的数.. k为k个链表
并且学习了优先队列的比较器如何写......

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    struct cmp
    {
        bool operator() (const ListNode* a,const ListNode* b)
        {
            return a->val  > b->val;
        }
    };
    
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode*,vector<ListNode*>, cmp> que;
        for(int i=0; i<lists.size(); i++) {
            if(lists[i])
                que.push(lists[i]);
        }
        ListNode *first = new ListNode(-0x3f3f3f3f);
        ListNode *cur = first;
        while(!que.empty()) {
            ListNode *top = que.top();
            que.pop();
            if(top) {
                first->next = top;
                first = first->next;
                if(first && first->next) {
                    que.push(first->next);
                }    
            } 
        }
        // first->next = NULL;
        return cur->next;
    }
};