My 100% submission C++


  • 1
    C
    ListNode *mergeTwoLists(ListNode *a, ListNode *b) {
        if(!a) return b;
        if(!b) return a;
        
        ListNode *p1 = a->val < b->val ? a : b;
        ListNode *p2 = a->val >= b->val ? a : b;
        ListNode *pre1 = p1;
        ListNode *pre2 = p2;
        
        while(p1 && p2) {
            if(p1->val < p2->val) {
                pre1 = p1;
                p1 = p1->next;
            }
            else {
                pre2 = p2->next;
                p2->next = pre1->next;
                pre1->next = p2;
                pre1 = pre1->next;
                p2 = pre2;
            }
        }
        
        if(p2) {
            pre1->next = p2;
        }
        
        return a->val < b->val ? a : b;
    }
    
    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            int len = lists.size();
            ListNode *temp;
            for(int i = 0;i < len;i ++) {
                temp = mergeTwoLists(temp, lists[i]);
            }
            
            return temp;
        }
    };

Log in to reply
 

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