educative.io

Educative

Can there be a recursive solution to the merge two linkedlist probem as well?

Can there be a recursive solution to the merge two linkedlist problem as well?

I’m not sure which problem you are referring to but you can merge two linked lists using recursion.
I think the following code should work:

Node* SortedMerge(Node* a, Node* b)
{
	Node* result = NULL;
	
	/* Base cases */
	if (a == NULL)
		return(b);
	else if (b == NULL)
		return(a);
	
	/* Pick either a or b, and recur */
	if (a->data <= b->data)
	{
		result = a;
		result->next = SortedMerge(a->next, b);
	}
	else
	{
		result = b;
		result->next = SortedMerge(a, b->next);
	}
	return(result);
}

// This code is contributed by rathbhupendra

This is C++ by the way.