23. Merge k Sorted Lists

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<pair<int,ListNode*>> q;
        for (auto p : lists)
            if (p)
                q.push({-p->val, p});
        
        ListNode h(0);
        ListNode *cur = &h;
        while (!q.empty()) {
            auto p = q.top().second;
            q.pop();
            
            cur->next = p;
            cur = p;
            if (p->next) {
                q.push( {-p->next->val, p->next} );
            }
        }
        cur->next = NULL;
        return h.next;
    }
};

 

posted @ 2018-05-18 14:09  JTechRoad  阅读(82)  评论(0编辑  收藏  举报