Leetcode 23. Merge K ascending linked lists

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

It is mainly used to contact the code writing of pointers and classes.

Because the system gives the function structure, you cannot reconstruct the new linked list yourself, because the memory space occupied by the local variables will be released after leaving the function scope. Therefore, the value of next can only be modified on the original linked list to reconstruct the linked list.

Mainly used the priority queue (minimum heap) maintenance.

Code:


```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;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43180746/article/details/115007313