23. Merge k Sorted Lists***

23. Merge k Sorted Lists***

https://leetcode.com/problems/merge-k-sorted-lists/

Title Description

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

C ++ implementation 1

Minimum heap process. Note that the input may be [nullptr]the case, so in the following code, added to the if (l)judgment.

class Solution {
private:
    struct Comp {
        bool operator()(ListNode *p1, ListNode *p2) {
            return p1->val > p2->val;
        }
    };
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode*, vector<ListNode*>, Comp> q;
        ListNode *dummy = new ListNode(0);
        auto ptr = dummy;
        for (auto &l : lists)
            if (l)
                q.push(l);

        while (!q.empty()) {
            auto l = q.top();
            q.pop();
            ptr->next = l;
            ptr = ptr->next;
            if (l->next) q.push(l->next);
        }
        return dummy->next;
    }
};

Published 455 original articles · won praise 8 · views 20000 +

Guess you like

Origin blog.csdn.net/Eric_1993/article/details/104860574