Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
1.6 kB
1
Indexable
Never
/**
 * 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:
   ListNode* merge2lists(ListNode* l1, ListNode* l2){
        if(!l1) return l2;
        if(!l2) return l1;
        if(l1->val <=l2->val){
            l1->next=merge2lists(l1->next,l2);
            return l1;
        }else{
            l2->next=merge2lists(l1,l2->next);
            return l2;
        }
    }

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        
        if(lists.empty()) return nullptr; //if i use a different vector then it wont be stitched entirely

        while(lists.size()>1){
            lists.push_back(merge2lists(lists[0],lists[1]));
            lists.erase(lists.begin());
            lists.erase(lists.begin());
        }
        return lists.front();
    }
};
/* 
The error in your code is that you are not updating the lists vector with the merged lists stored in the res vector. After merging two lists, you are storing the result in res but you are not using these results for the next merge operations.
In this corrected code, after merging two lists, the result is added to the end of lists. The two merged lists are then removed from lists. This process continues until lists contains only one element, which is the fully merged list. This list is then returned by the mergeKLists function. */
Leave a Comment