my c++ solution base on queue


  • 0
    Z

    my c++ solution base on queue

    ListNode* mergeKLists(vector<ListNode*>& lists) {
      if (lists.empty()) {
        return NULL;
      }
    
      queue<ListNode*> queues;
      for (auto& node : lists) {
        queues.push(node);
      }
      while (queues.size() > 1) {
        ListNode* l1 = queues.front();
        queues.pop();
        ListNode* l2 = queues.front();
        queues.pop();
        ListNode* newNode = mergeTwoLists(l1, l2);
        if (newNode) {
            queues.push(newNode);
        }
      }
      return queues.front();
    }
    
    
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
      {
            if (!(l1 && l2)) {
                if (l1) {
                    return l1;
                }
                return l2;
            }
            
            ListNode* l1Helper = l1;
            ListNode* l2Helper = l2;
            ListNode* currentNode = NULL;
            ListNode* newHead = NULL;
            //init
            
            if (l1->val < l2->val) {
                currentNode = l1;
                l1 = l1->next;
            } else {
                currentNode = l2;
                l2 = l2->next;
            }
            newHead = currentNode;
            while (l1 && l2) {
                ListNode* lessNode;
                if (l1->val < l2->val) {
                    lessNode = l1;
                    l1 = l1->next;
                } else {
                    lessNode = l2;
                    l2 = l2->next;
                }
                currentNode->next = lessNode;
                if (currentNode->next) {
                    currentNode = currentNode->next;
                }   
                
                
            }
            if (l1) {
                currentNode->next = l1;
                return newHead;
            }
            currentNode->next = l2;
            return newHead;
            
        }
    }
    

Log in to reply
 

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