knakul853

Untitled

Jun 18th, 2020
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. /**
  2. knakul853
  3.  */
  4. class Solution {
  5. public:
  6.     ListNode* mergeKLists(vector<ListNode*>& lists) {
  7.        
  8.         if( lists.size() < 1) return NULL;
  9.        
  10.         while(lists.size() > 1)
  11.         {
  12.            ListNode* temp = merge(lists[0], lists[1]);
  13.             lists.erase(lists.begin());
  14.             lists.erase(lists.begin());
  15.             lists.push_back(temp);
  16.         }
  17.        
  18.         return lists[0];
  19.        
  20.     }
  21.    
  22.     ListNode* merge(ListNode* l1, ListNode* l2)
  23.     {
  24.         if( !l1 ) return l2;
  25.         if(!l2) return l1;
  26.        
  27.         if(l1->val <= l2->val)
  28.         {
  29.             l1->next = merge(l1->next, l2);
  30.             return l1;
  31.         }
  32.        
  33.         else{
  34.            
  35.             l2->next = merge(l1, l2->next);
  36.             return l2;
  37.         }
  38.     }
  39. };
Add Comment
Please, Sign In to add comment