Merge K sorted LinkedList into one sorted LinkedList

Problem Link

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

/*You are required to complete this function*/
node * mergeKList(node *arr[],int N)
{
//Your code here
    node *headArray[11];
    node *tmpNodes[11];
    node *newHead,*tmp,*t;

	for(int i=0;i<=N;i++)
	{
		tmpNodes[i]=arr[i];
	}
	bool f=1;
	bool first=0;
	while(f)
	{
		int min=10000000;
		int lastIdx=-1;
		f=0;
		for(int i=0;i<=N;i++)
		{
			if(tmpNodes[i]!=NULL)
			{
				f=1;
				if(min>tmpNodes[i]->data)
				{
					min=tmpNodes[i]->data;
					lastIdx=i;
				}
			}
		}
		if(lastIdx<0)
			break;
		if(first==0)
		{
		    tmp=tmpNodes[lastIdx];
			newHead=tmp;
			first=1;
		}
		else
		{
			tmp->next=tmpNodes[lastIdx];
			tmp=tmp->next;
		}
		tmpNodes[lastIdx]=tmpNodes[lastIdx]->next;
	}
	return newHead;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *