Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *mergeKLists(vector<ListNode *> &lists) { // Start typing your C/C++ solution below // DO NOT write int main() function int n = lists.size() ; if(n == 0) return NULL; if(n == 1) return lists[0]; int *flag = new int[n] ; ListNode **list = new ListNode *[n] ; int i,min ; for(i = 0; i<n;i++) { if(lists[i] == NULL) flag[i] = 0; else flag[i] = 1; list[i] = lists[i]; } bool stop = true; ListNode *head = NULL, *current; while(stop) { for(i = 0; i<n &&flag[i] == 0; i++) ; if(i == n) break; min = i ; for(i++;i<n ;i++) { if(flag[i]== 0) continue; if(list[i]->val < list[min]->val) min = i; } if(head == NULL) { head = list[min]; current = list[min]; }else { current->next = list[min]; current = list[min]; } list[min] = list[min]->next; if(list[min] == NULL) flag[min] = 0; }// end of while return head; } };