So basically, I have to merge two linked lists (passed as parameters) into a third linked list (also passed in as a parameter) - but by the end of the function the new list must still be sorted and the other linked lists must be empty. I'm pretty sure I'm close, but for some reason I don't think the third list is being computed correctly. If anyone could take a look and tell me where I'm wrong real quick that would be awesome, considering I'm not to good at recursion. By the end, headX and headY should be both be empty, with all of their items sorted in headZ. However, after the function is done, headZ is not correct (though I'm not sure why).
void sortedMergeRecur(Node* &headX, Node* &headY, Node* &headZ)
{
// we can assume that both headx and heady are sorted linkedlists
// first establish base case or when to stop
if((headX == 0) && (headY != 0))
{
// x is empty, but y is not
headZ = headY;
headY = 0;
return;
}
else if((headY == 0) && (headX != 0))
{
// y is empty, but x is not
headZ = headX;
headX = 0;
return;
}
else if((headY == 0) && (headX == 0))
{
// if they're both empty, we don't need to add anything z
headZ = 0;
return;
}
// Pick either x or y to add
if (headX->data <= headY->data)
{
headZ = headX;
SortedMergeRecur(headX->link, headY, headZ->link);
headX = 0;
}
else // if(headX->data > headY->data)
{
headZ = headY;
SortedMergeRecur(headX, headY->link, headZ->link);
headY = 0;
}
return;
}
Node *x = new Node{ 1, new Node{ 7, nullptr } }; Node *y = new Node{ 0, new Node{ 7, new Node{ 7, nullptr } } };(you'll need a C++11 compiler for that)