A C++ solution


  • 0
    W
    class Solution 
    {
    public:
        
        ListNode *merge(ListNode *a, ListNode *b)
        {   
            if(!a||!b)
                return a?a:b;
                        
            if(a->val > b->val)
                swap(a, b);
            auto head=a;
            for(; a && b; a=a->next)
            {
                if(!a->next || a->next->val > b->val)
                    swap(a->next, b);
            }
            return head;
        }
        
        ListNode* mergeKLists(vector<ListNode*> &lists) 
        {
            for(int i=1; i<lists.size(); ++i)
                lists[0] = merge(lists[0],lists[i]);
            return lists.size() ? lists[0] : nullptr;
        }
    };
    

Log in to reply
 

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