And also 2 singly linked lists of type Node objects (pointed by "head1" and "head2"), sorted in ascendent order by "name".
Now I want to merge those two lists into a static array (knowing that there will never be more than 1000 elements in both lists), still sorted by name. The thing is, I don't know beforehand how many elements the lists have and they might not be of the same size. I thought of something like this: start iterating over the lists, node by node and comparing them to find the lesser value and inserting it into the array. As soon as one of the lists reaches its end, I continue iterating over the other one, inserting each element in the array.
This is my code, but I feel it has many duplicate instructions and that maybe there's a better way to work it out:
ExampleObject staticArray[1000];
int i=0;
while ((i!=1000) and (head1!=nullptr) and (head2!=nullptr)){
if (head1->exampleObject.name < head2->exampleObject.name){
staticArray[i]=head1->exampleObject;
head1=head1->next;
}
else{
staticArray[i]=head2->exampleObject;
head2=head2->next;
}
i++;
}
if (head1==nullptr)
while ((head2!=nullptr) and (i!=1000)){
staticArray[i]=head2->exampleObject;
head2=head2->next;
i++;
}
elseif (head2==nullptr)
while ((head1!=nullptr) and (i!=1000)){
staticArray[i]=head1->exampleObject;
head1=head1->next;
i++;
}
Is there a better way to re-write these instructions into a more "condensed" way to tidy it up a bit (but without changing the list structure I'm using)?