Merge K sorted linked lists

PROBLEM :

Given K sorted linked list your task is to merge them .You need to complete mergeKList  method that takes 2 arguments the arr [ ] that represents an array of  sorted linked list and an integer N denoting the no of sorted linked list  and returns the head of the obtained linked list. There are multiple test cases. For each test case, this method will be called individually.

Input:
The first line of input will denote the no of Test cases then T test cases will follow . Each test cases will contain an integer N denoting the no of sorted linked list. Then in the next line all of the nodes of the linked list are fed to the input in a fashion where first integer will denote no of nodes of one of the sorted linked list and then all the elements of the linked list separated by space .

Output:
The output will be the nodes of the merged linked list .

Constraints
1<=T<=50
1<=N<=10

Example:

Input
1
4
3 1 2 3 2 4 5 2 5 6 2 7 8

Output:
1 2 3 4 5 5 6 7 8

Explanation
above test case has 4 sorted linked list of size 3, 2, 2, 2
1st      list     1 -> 2-> 3
2nd    list      4->5
3rd     list      5->6
4th     list      7->8
The merged list will be 1->2->3->4->5->5->6->7->8
     
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*Linked list node structure
struct node
{
    int data;
    struct node* next;
};*/

/*You are required to complete this function*/

node* mearge(node *,node *) ;

node * mergeKList(node *arr[],int N)
{
    while(N!=0)
    {
        int i,j ;
        i=0 ;
        j=N ;
   
        while(i<j)
        {
            arr[i]=mearge(arr[i],arr[j]) ;
            i++ ;
            j-- ;
           
            if(j<=i)
                N=j ;
        }
    }
   
    return arr[0] ;
}

node* mearge(node *first,node *second)
{
    if(first==NULL)
        return second ;
       
    if(second==NULL)
        return first ;
   
    node *final ;
   
    if(first->data<second->data)
    {
        final=first ;
        final->next=mearge(first->next,second) ;
    }
    else
    {
        final=second ;
        final->next=mearge(first,second->next) ;
    }
   
    return final ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )