104. Merge K Sorted Lists
Description:
Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.
Example
Example 1:
Input: [2->4->null,null,-1->null]
Output: -1->2->4->null
Example 2:
Input: [2->6->null,5->null,7->null]
Output: 2->5->6->7->null
Main Idea:
It’s the follow-up question of merge two list. Thus, all we need is to iterate the vector n times to merge two lists.
Tips/Notes:
- Don’t make mistake when writing merge two list.
Code:
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
ListNode *mergeKLists(vector<ListNode *> &lists) {
// write your code here
ListNode* dummy = new ListNode(-1);
ListNode* tmp = dummy;
for(auto now : lists){
tmp->next = mergeTwoLists(tmp->next, now);
}
return dummy->next;
}
ListNode* mergeTwoLists(ListNode * l1, ListNode * l2) {
// write your code here
ListNode* dummy = new ListNode(-1);
ListNode* tmp = dummy;
while(l1 || l2){
if(l1 == nullptr){
tmp->next = l2;
return dummy->next;
}
if(l2 == nullptr){
tmp->next = l1;
return dummy->next;
}
if(l1->val <= l2->val){
tmp->next = l1;
tmp = tmp->next;
l1 = l1->next;
}
else{
tmp->next = l2;
tmp = tmp->next;
l2 = l2->next;
}
}
return dummy->next;
}
};