Simple C++


  • 0
    G
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            struct cmp {
                bool operator () (ListNode* a, ListNode* b) {
                    return (a->val > b->val);
                }
            };
            priority_queue<ListNode*, vector<ListNode*>, cmp> minHeap;
            for (int i = 0; i < lists.size(); i++) {
                if (lists[i]) minHeap.push(lists[i]);
            }
            ListNode* head = NULL, *tail = NULL;
            while (!minHeap.empty()) {
                ListNode* min = minHeap.top();
                minHeap.pop();
                if (!head) {
                    head = tail = min;
                } else {
                    tail->next = min;
                    tail = min;
                }
                if (min->next) minHeap.push(min->next);
            }
            return head;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.