LeetCode 23. Merge k Sorted Lists

题目链接
n是总共的数.. k为k个链表
并且学习了优先队列的比较器如何写......

/**
 * 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() (const ListNode* a,const ListNode* b)
        {
            return a->val  > b->val;
        }
    };
    
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode*,vector<ListNode*>, cmp> que;
        for(int i=0; i<lists.size(); i++) {
            if(lists[i])
                que.push(lists[i]);
        }
        ListNode *first = new ListNode(-0x3f3f3f3f);
        ListNode *cur = first;
        while(!que.empty()) {
            ListNode *top = que.top();
            que.pop();
            if(top) {
                first->next = top;
                first = first->next;
                if(first && first->next) {
                    que.push(first->next);
                }    
            } 
        }
        // first->next = NULL;
        return cur->next;
    }
};
posted @ 2019-04-23 16:39  Draymonder  阅读(103)  评论(0编辑  收藏  举报