23合并k个升序链表

学习了优先权队列的使用方法,引入头文件,写一个比较函数,可以当作最小堆、最大堆使用

#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;



 struct ListNode {
	int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
 };

 class Solution {
 public:
     struct Status {
         int value;
         ListNode* ptr;
         bool operator < (const Status& that) const {
             return value > that.value; //最大堆,反之最小堆
         }
     };
     priority_queue <Status> q;
     ListNode* mergeKLists(vector<ListNode*>& lists) {
         for (auto node : lists) {
             if (node) q.push({ node->val, node });  // 在优先权队列中依次插入各个list首节点
         }
         ListNode head, * tail = &head;
         while (!q.empty()) {
             auto f = q.top(); q.pop(); //f是优先级队列中弹出的最大status
             tail->next = f.ptr;
             tail = tail->next; //最大的放最后面
             if (f.ptr->next) q.push({ f.ptr->next->val, f.ptr->next });
         }
         return head.next;
     }
 };

int main() {
	Solution test;
    ListNode* a = new ListNode(1);
    a->next= new ListNode(4);
    a->next->next = new ListNode(5);
    ListNode* b = new ListNode(1);
    b->next = new ListNode(3);
    b->next->next = new ListNode(4);
    ListNode* c = new ListNode(2);
    c->next = new ListNode(6);
    vector<ListNode*>lists(3);
    lists.push_back(a);
    lists.push_back(b);
    lists.push_back(c);
    ListNode* ans = test.mergeKLists(lists);
    while (ans) {
        cout << ans->val<<" ";
        ans = ans->next;
    }

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值