I would do a couple of things differently.
###Early escape
Early escape
Your use of early escape is good and makes the code easier to read but you don't need the else section if the body of if statement returns.
Node* merge(Node* list1, Node* list2)
{
if (list1 == nullptr){
return list2;
}
if (list2 == nullptr){
return list1;
}
// Main body of code.
This is quite normal. It reduces the number of level of indenting and makes the code look clean.
Self documenting code
I would encourage you to split getting the next item into a separate function (this facilitates self documenting code).
Node* getNextNode(Node*& list1, Node*& list2)
{
// Work out which list has the smallest value.
Node*& smallList = (list1->data < list2->data) ? list1 : list2;
// The head of this list is the result
Node* result = smallList;
// Move the list to the next value (notice the call be reference).
smallList = smallList->next;
return result;
}
Simplified Body
Now if we rewrite the main body of your code in terms of this helper function;
Node* result = getNextNode(list1, list2);
Node* current = result;
// Looping over the list until one is empty
// becomes very trivial now.
while(list1 != nullptr && list2 != nullptr)
{
// Get next node and remove it from its list.
Node* next = getNextNode(list1, list2);
current->next = next;
current = next;
}
// One of the lists is empty.
// Add what is left of the other list on the end (ie after current).
current->next = (list1 == nullptr) ? list2 : list1;
return result;