Approach

This is actually quite simple, just take the smallest from all list and connect, and iteratively do this process, and will use a min heap instead for faster min-val query.

I also tried a new method for defining the comparator for priority_queue this time. Usually I will use a comparator class and a bool operator(), but I found that there is a more clear way to write this, that is to define the lambda function first, and pass the function to pq’s constructor.

Code

class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {     
        auto cmp = [](ListNode* a, ListNode* b) {
            return a->val > b->val; // min-heap
        };
        priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> pq(cmp);
        for(int i = 0 ; i < lists.size() ; ++i) {
            if(lists[i] != nullptr) pq.push(lists[i]);
        }
        ListNode dummy;
        ListNode* head = &dummy;
        while(!pq.empty()) {
            ListNode* node = pq.top();
            ListNode* next = node->next;
            pq.pop();
            if(next != nullptr) pq.push(next);
            head->next = node;
            head = node;
        }
        return dummy.next;
    }
};