Merge k Sorted Lists [LeetCode]

时间:2021-09-30 09:53:14

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Summary:  Finds the smallest node every round, then links it to the one sorted list.

     ListNode *mergeKLists(vector<ListNode *> &lists) {
ListNode * head = NULL;
ListNode * pre_node = NULL;
while(true){
//find the smallest one
ListNode * smallest_node = NULL;
for(auto item : lists) {
if(item != NULL){
if(smallest_node == NULL || item->val < smallest_node->val )
smallest_node = item;
}
}
if(smallest_node == NULL)
break; if(pre_node == NULL){
pre_node = smallest_node;
head = pre_node;
}else{
pre_node -> next = smallest_node;
pre_node = pre_node -> next;
} for(int i = ; i< lists.size(); i ++){
if(lists[i] == smallest_node)
lists[i] = lists[i] -> next;
}
}
return head;
}