Leetcode 23. 合并K个升序链表

题目链接:https://leetcode-cn.com/problems/merge-k-sorted-lists/

主要用来联系一下指针、类的代码写法。

因为系统给了函数结构,所以,不能自己重构新的链表,因为在离开函数作用域之后局部变量占用的内存空间会被释放掉。所以只能在原链表上修改next的值,从而重构链表。

主要是用了优先队列(最小堆)维护的。

代码:


```cpp
/**
 * 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 Status {
    
    
        int val;
        ListNode *ptr;
        Status(int val,ListNode *ptr):val(val),ptr(ptr) {
    
    };
        bool operator < (const Status &rhs) const {
    
    
            return val > rhs.val;
        }
    };

    priority_queue <Status> q;

    ListNode* mergeKLists(vector<ListNode*>& lists) {
    
    
        for(int i=0;i<lists.size();i++)
        {
    
    
            ListNode *x = lists[i];
            if(x)
            	q.push(Status(x->val,x));
        }
        ListNode head;
        ListNode *tail = &head;
        while(!q.empty())
        {
    
    
            Status x = q.top();
            q.pop();
            tail->next = x.ptr;
            tail = tail->next;
            if(x.ptr->next)
                q.push(Status(x.ptr->next->val,x.ptr->next));
        }
        tail->next =nullptr;
        return head.next;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43180746/article/details/115007313