I need to copy two linked lists recursively and return a new list. The way I need to copy them is one element from list1, one from the list2. If one list is shorter than the other just append the remaining elements of the longer list.
Example input: list1 = [1,2,3], list2 = [4,5,6,7]; result = [1,4,2,5,3,6,7];
Here’s my defective (now correct) code:
node *copy(node *list1, node *list2)
{
if (list1 == NULL && list2 == NULL) return NULL;
else if (list1 != NULL && list2 != NULL) {
node *result;
result = newnode();
result->data = list1->data;
result->next = newnode();
result->next->data = list2->data;
result->next->next = copy(list1->next, list2->next);
return result;
}
else if (list1 != NULL && list2 == NULL) {
node *result;
result = newnode();
result->data = list1->data;
result->next = copy(list1->next, NULL);
return result;
}
else if (list1 == NULL && list2 != NULL) {
node *result;
result = newnode();
result->data = list2->data;
result->next = copy(NULL, list2->next);
return result;
}
}
Can someone point the mistakes I’m making ?
Edit: Now it works. I was missing two return statements.
You seem to be missing return statements in the bottom two else if branches.