小根堆的链表运用Leetcode 023合并K个有序链表(基于021合并两个有序链表)

地址

https://leetcode-cn.com/problems/merge-k-sorted-lists/

描述

在这里插入图片描述

思想

核心思想为碰到链表结构体怎么定义小根堆
以及021题的合并链表思想。

代码

/**
 * Definition for singly-linked list.
 * 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 Cmp{
    
    
        bool operator () (ListNode *a,ListNode *b){
    
    
            return a->val > b->val;
        }
    };
    ListNode* mergeKLists(vector<ListNode*>& lists) {
    
    
        ListNode *dummy=new ListNode (-1),*tail=dummy;
        //自定义比较函数的方式定义小根堆
        priority_queue<ListNode*,vector<ListNode*>,Cmp> heap;
        for(ListNode *l:lists)
            if(l) heap.push(l);//假如l链表非空,加入小根堆,堆顶是第一个元素最小的链表
            //堆里面没有链表说明,合并结束
            while(heap.size()){
    
    
                ListNode *t=heap.top();
                heap.pop();
                tail=tail->next=t;
                if(t->next) heap.push(t->next);//把新的链表头加入heap,重新进行排序
            }
        return dummy->next;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_52934831/article/details/121359822