A simple c solution


  • 0
    C
    struct ListNode* mergeKLists(struct ListNode** lists, int listsSize)
    {
      struct ListNode *head, *tail, *min_node;
      int i, index;
    
      if (lists == NULL || listsSize <= 0)
        return NULL;
    
      if (listsSize == 1)
        return lists[0];
    
      tail = head = NULL;
      for ( ;; ) {
        min_node = NULL;
        for (i = 0; i < listsSize; i++) {
          if (lists[i] && (min_node == NULL || lists[i]->val < min_node->val)) {
            min_node = lists[i];
            index = i;
          }
        }
        if (min_node == NULL)
          break;
    
        if (head == NULL) {
          tail = head = min_node;
        } else {
          tail->next = min_node;
          tail = min_node;
        }
        lists[index] = min_node->next;
        tail->next = NULL;
      }
    
      return head;
    }
    

Log in to reply
 

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