Simple C++ Solution Merging Two Lists in a Loop Each Step


  • 0
    M
    class Solution {
    public:
        ListNode* Merge(ListNode* l1, ListNode* l2) {
            ListNode * result = 0;
            ListNode ** last = &result;
            while (l1 && l2) {
                ListNode *& lmin = l1->val < l2->val ? l1 : l2;
                *last = lmin;
                lmin = lmin->next;
                last = &(*last)->next;
            }
            *last = l1 ? l1 : l2;
            return result;
        }
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            if (lists.empty()) return 0;
            while (lists.size() > 1) {
                lists.push_back(Merge(lists[0], lists[1]));
                lists.erase(lists.begin(), lists.begin() + 2);
            }
            return lists.front();
        }
    };
    

Log in to reply
 

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