【力扣 012】23. 合并K个升序链表

23. 合并K个升序链表

解法1:

 1 class Solution {
 2 public:
 3     ListNode* mergeKLists(vector<ListNode*>& lists) 
 4     {
 5         auto cmp = [](ListNode*& a, ListNode*& b) 
 6         {
 7             return a->val > b->val;
 8         };
 9         priority_queue<ListNode*, vector<ListNode*>, decltype(cmp) > q(cmp);
10         for (auto node : lists) 
11         {
12             if (node) q.push(node);
13         }
14         ListNode *dummy = new ListNode(-1), *cur = dummy;
15         while (!q.empty()) 
16         {
17             auto t = q.top(); q.pop();
18             cur->next = t;
19             cur = cur->next;
20             if (cur->next) q.push(cur->next);
21         }
22         return dummy->next;
23     }
24 };

 

posted @ 2021-11-09 21:13  苏格拉底的落泪  阅读(28)  评论(0编辑  收藏  举报