Routine to merge two linked lists together and return a new merged list. One optimization I can think of is passing by reference instead of value. Any other suggestions ? Is there a shorthand to make lines 4 and 5 single/shorter?
template<class t>
Linkedlist<t> merge(Linkedlist<t> firstList, Linkedlist<t> secondList) {
/*4*/ Node<t>Node<int> * current = ( firstList.head->data < secondList.head->data ) ? firstList.head : secondList.head;
/*5*/ Node<t>Node<int> * other = ( firstList.head->data > secondList.head->data ) ? firstList.head : secondList.head;
Node<t>Node<int> * oldOther = nullptr;
Node<t>Node<int> * oldNext = nullptr;
while ( current && other ) {
if ( current->next == nullptr || current->next->data > other->data ) {
oldOther = other;
oldNext = current->next;
current->next = other;
other = oldNext;
current = oldOther;
} else {
current = current->next;
}
}
return ( firstList.head->data < secondList.head->data ) ? firstList : secondList;
}