My answer with Cpp which merge K Lists by merge Two Lists -- recursion


  • 0
    Z

    ListNode* mergeTwoLists(ListNode *l1, ListNode *l2)
    {
    ListNode *t;
    vector<int> l;
    if (l1 == NULL && l2 == NULL) {cout << "d" << endl; return NULL;}
    if (l1 == NULL && l2 != NULL) {cout << 'e' << endl; return l2;}
    if (l1 != NULL && l2 == NULL) {cout << 'f' << endl; return l1;}

     if (l1->val < l2->val) {
          l.push_back(l1->val);
          l1 = l1->next;
     }
     else {
          l.push_back(l2->val);
          l2 = l2->next;
     }
    
     while (l1 != NULL && l2 != NULL) {
          if (l1->val < l2->val) {
               l.push_back(l1->val);
               l1 = l1->next;
          }
          else {
               l.push_back(l2->val);
               l2 = l2->next;
          }
     }
    
     while (l1 != NULL) {
          l.push_back(l1->val);
          l1 = l1->next;
     }
    
     while (l2 != NULL) {
          l.push_back(l2->val);
          l2 = l2->next;
     }
    
     t = new ListNode(l[0]);
     ListNode *tmp = t;
     for (int i = 1; i < l.size(); ++i) {
          tmp->next = new ListNode(l[i]);
          tmp = tmp->next;
     }
    
     return t;
    

    }

    ListNode* mergeKLists(vector<ListNode*>& lists)
    {
    if (lists.size() == 0) return NULL;

     if (lists.size() == 1) return lists[0];
    
     int i = 0;
     vector<ListNode*> newLists;
     while (i < lists.size()-1) {
          ListNode *l = mergeTwoLists(lists[i], lists[i+1]);
          newLists.push_back(l);
          i += 2;
     }
     if (i == lists.size()-1) newLists.push_back(lists[i]);
    
     return mergeKLists(newLists);
    

    }


Log in to reply
 

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