jeudi 15 juillet 2021

C++ linked list merging using multimap [closed]


/**
 * 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) {}
 * };
 */

 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* h1=l1;
        ListNode* h2=l2;
        ListNode* nodes=new ListNode();
       ListNode* ret=nodes;
        int i=0;
        multimap<int,ListNode*> sorted;
        while(h1!=nullptr || h2!=nullptr){           
            if(h1!=nullptr)
            {
                sorted.insert({h1->val,h1});
                h1=h1->next;
            }    
            if(h2!=nullptr)
            {
                sorted.insert({h2->val,h2});
                h2=h2->next;
            }
            i++;
        }
        for (auto itr = sorted.begin(); itr != sorted.end(); itr++){
            if(++itr==sorted.end()){
                itr--;
                nodes->val=itr->first;
                
            }
            nodes->val=itr->first;
            nodes->next=new ListNode();
            nodes=nodes->next;
        }
        
        return ret;
    }

Your input: l1= [1,2,4] l2= [1,3,4]

Output [1,2,4] Expected [1,1,2,3,4,4]

if i comment out marked lines

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* h1=l1;
        ListNode* h2=l2;
        ListNode* nodes=new ListNode();
       ListNode* ret=nodes;
        multimap<int,ListNode*> sorted;
        while(h1!=nullptr || h2!=nullptr){           
            if(h1!=nullptr)
            {
                sorted.insert({h1->val,h1});
                h1=h1->next;
            }    
            if(h2!=nullptr)
            {
                sorted.insert({h2->val,h2});
                h2=h2->next;
            }   
        }
        for (auto itr = sorted.begin(); itr != sorted.end(); itr++){
            //changhes here 
            nodes->val=itr->first;
            nodes->next=new ListNode();
            nodes=nodes->next;
        }
        
        return ret;
    }

Your input : l1= [1,2,4]

        l2= [1,3,4]

Output [1,1,2,3,4,4,0] Expected [1,1,2,3,4,4]

I know that, the last zero is caused by the last iteration . to resolve that issue, I tried the above hack but it gives all another output. please help. Multimap allows duplicate values then why this Unexpected behaviour

Aucun commentaire:

Enregistrer un commentaire