I solved this problem in C++. I was having trouble though understanding what return headA; and return headB; returns after going back down the recursion tree. A code review is also appreciated!
You’re given the pointer to the head nodes of two sorted linked lists. The data in both lists will be sorted in ascending order. Change the next pointers to obtain a single, merged linked list which also has data in ascending order. Either head pointer given may be null meaning that the corresponding list is empty.
/*
Merge two sorted lists A and B as one linked list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
#include <iomanip>
Node* MergeLists(Node *headA, Node* headB)
{
// check if either linked list is empty, then return the other one. when doing recursive, a new headA and headB will be passed in, so it will add the entire list correctly
if (headA == NULL) {
return headB;
} else if (headB == NULL) {
return headA;
} else { // if neither empty go into this block
if (headA->data <= headB->data) {
headA->next = MergeLists(headA->next, headB);
// returns the entire linked list after the recursion parses it in the correct order
// not too sure what is returned going down the recursion tree
// headA = 1 -> 3 -> 5 -> 6 -> NULL
// headB = 2 -> 4 -> 7 -> NULL
// would it return 6, 5, 3, 1, 1->2->3->4->5->6->7 after recursion tree?
return headA;
} else {
headB->next = MergeLists(headA, headB->next);
// return 7, 4, 2 after recursion tree?
return headB;
}
}
}