Merge k Sorted Lists, Leetcode

 Statement - 

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

 

Example 1:

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
  1->4->5,
  1->3->4,
  2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6

Code - 
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* kmerge(ListNode *b, ListNode *a)
    {
        if(!a) return b;
        if(!b) return a;
        
        ListNode *temp = NULL;
        
        if(a->val <= b->val)
        {
            temp = a;
            temp->next = kmerge(b, a->next);
        }
        else
        {
            temp = b;
            temp->next = kmerge(b->next, a);
        }
        
        return temp;
    }
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        
        if(lists.size() < 1) return NULL;
        
        ListNode *ans = NULL;
        
        for(auto a : lists)
        {
            ans = kmerge(ans, a);
        }
        
        return ans;
        
    }
};

Offers

Reactions

Post a Comment

0 Comments