Clean yet efficient solution in C++


  • 1
    class Solution {
    private:
        ListNode* merge(ListNode* l1, ListNode* l2)
        {
            ListNode newHead(0);
            ListNode *t = &newHead;
            while(l1 || l2)
            {
                if(!l1) { t->next = l2; break; }
                if(!l2) { t->next = l1; break; }
                if(l1->val <= l2->val)
                {
                    t->next = l1;
                    l1 = l1->next;
                }
                else
                {
                    t->next = l2;
                    l2 = l2->next;
                }
                t = t->next;
            }
            return newHead.next;
        }
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) 
        {
            if(lists.empty()) return NULL;
            while(lists.size() > 1)
            {
                vector<ListNode*> lists1;
                while(lists.size())
                {
                    ListNode *l1 = lists.back();
                    lists.pop_back();
                    if(lists.empty()) { lists1.push_back(l1); break; }
                    ListNode *l2 = lists.back();
                    lists.pop_back();
                    lists1.push_back(merge(l1, l2));
                }
                lists.swap(lists1);
            }
            return lists.back();
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.