I see a number of things which may help you improve your code.
Make template arguments consistent
Your Merge
routine takes a pair of Linkedlist<T>
arguments, but then seems to assume that they are really Linkedlist<int>
because of the Node<int>
declarations. If you're going to use a template, make sure it's consistent and useful.
Don't directly manipulate object data
The code seems to assume that all member data items are public which is generally not a good design. A better idea is to use accessors or functions to allow safer object operation and to allow different kinds of objects to be used. In this case, it was not that easy to review the code because the interface was not fully specified.
Avoid the use of raw pointers
In modern C++, raw pointers are generally an indicator that your design could likely be improved. In this case, for example, what happens if your code is passed an empty list? The likely result will be a crash because the first thing the code does is to dereference the head
pointer. If that pointer is nullptr
then a crash is a likely result.
Prefer to pass by reference
The lists probably don't actually need to be copied to perform the merge. For that reason, it would be better to declare the function as:
Linkedlist<t> merge(const Linkedlist<t> &firstList, const Linkedlist<t> &secondList) {
Decide which object owns the data
In the merge
code as implemented, two well formed lists are passed in and then their data is scrambled. When the temporary Linkedlist
parameter objects are deleted at the end of your function, all of their contents and pointers are invalidated making the returned list useless, since it will have references to deleted objects. This will result in a crash or memory leak at best.
Include test code in your review request
It's often much easier to review code if it is shown in context and with a complete interface. In this case, reviewers are left to reverse engineer the possible contents and operation of the Node<T>
and Linkedlist<T>
templates.
Consider implementing iterators
If your LinkedList
class implemented iterators, much of the messy pointer dereferencing would be eliminated and the code would be much easier to see and understand. It would also make it possible to use standard algorithms to manipulate your Linkedlist
class. See this question for hints on how to do that.