I have come upon a code, which entails recurcion, while I was studying linked lists. I don't know if the guy wrote the code the right way it's supposed to be. It handles the first case scenario --if one of the lists to be merged is is empty-- yet in further passes I don't see a condition to stop the recursion properly.
The condition that will stop the recurcion felt awkward to me and I thought I could ameliorate the code and come up with a better one. I don't know though if mine is perfectly correct.
Below this code I tried to improve on it in my own fashion, wrong however it might be.
Code:
struct node *SortedMerge3(struct node *a, struct node *b)
{
struct node *result;
if(a == NULL){
return b;
}
else if(b == NULL){
return a;
}
if(a->data <= b->data){
result = a;
result->next = SortedMerge3(a->next, b);
}
else{
result = b;
result->next = SortedMerge3(b->next, a);
return(result);
}
}
struct node *SortedMerge3(struct node *a, struct node *b)
{
struct node *result;
struct node dummy;
result = &dummyl;
dummy->next = NULL;
if(a == NULL){
result->next = b;
result = result->next;
return result;
}
else if(b == NULL){
result->next = a;
result = result->next;
return result;
}
if(a->data <= b->data){
result = a;
result->next = SortedMerge3(a->next, b);
}
else{
result = b;
result->next = SortedMerge3(b->next, a);
}
}