leetcode-23-链表题-合并K个排序链表

题目

leetcode-23-链表题-合并K个排序链表_第1张图片

解法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
// 同时比较所有链表的首节点,利用优先级队列,每次弹出最小值
class Solution {
public:
    // 定义比较操作
    struct cmp{
        bool operator()(ListNode *a, ListNode *b){
            return a->val > b->val;
        } 
    };

    ListNode* mergeKLists(vector& lists) {
        if(lists.empty()) return NULL;
		
        // 使用优先级队列,每次弹出最小值
        priority_queue , cmp> heapk;
        for(auto list : lists){
            if(list) heapk.push(list);
        }
        
        ListNode *res = new ListNode(-1);
        ListNode *tempRes = res;
        while(!heapk.empty()){
            ListNode *top = heapk.top();
            heapk.pop();
            tempRes->next = top;
            tempRes = tempRes->next;
            if(top->next) heapk.push(top->next);
        }

        tempRes = res->next;
        delete res;
        return tempRes;
    }
};

你可能感兴趣的:(leetcode-23-链表题-合并K个排序链表)