Merge k Sorted Lists
23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Subscribe to see which companies asked this question
23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Subscribe to see which companies asked this question
/** * 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) { ListNode *ans=new ListNode(0); for(int i=0;i<lists.size();i++){ ListNode *cur_ans=ans->next; ListNode *cur_answer=new ListNode(0); ListNode *cur=cur_answer; while(cur_ans && lists[i]){ if(lists[i]->val<cur_ans->val){ cur->next=lists[i]; lists[i]=lists[i]->next; cur=cur->next; } else{ cur->next=cur_ans; cur_ans=cur_ans->next; cur=cur->next; } } if(lists[i]){ cur->next=lists[i]; } if(cur_ans){ cur->next=cur_ans; } ans->next=cur_answer->next; } return ans->next; } };