首页 > 代码库 > LeetCode - Merge k Sorted Lists

LeetCode - Merge k Sorted Lists


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

class Solution {

public:
    struct compare {
    bool operator()(const ListNode* l, const ListNode* r) {
        return l->val > r->val;
    }
};
ListNode *mergeKLists(vector<ListNode *> &lists) { //priority_queue
    priority_queue<ListNode *, vector<ListNode *>, compare> key;
    for(int i = 0 ; i < lists.size() ; i ++){
            if(lists[i])
                key.push(lists[i]);
        }
        ListNode *head = new ListNode(0);
        ListNode *p = head;
        while(!(key.empty())){
            ListNode *fc = key.top();
            if(fc->next)
                key.push(fc->next);
            p->next = fc;
            p = fc;
            key.pop();
        }
    return head->next;
    }
};

LeetCode - Merge k Sorted Lists