leetcode-23-链表题-合并K个排序链表 发表于 2020-03-12 | 分类于 数据结构与算法 题目 解法123456789101112131415161718192021222324252627282930313233343536373839404142/** * 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<ListNode*>& lists) { if(lists.empty()) return NULL; // 使用优先级队列,每次弹出最小值 priority_queue<ListNode* ,vector<ListNode*> , 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; }};