class list
{
public:
int n;
list* next;
};
list* merge_sorted_lists(list* a, list* b)
{
list* t1;
list* t2;
list* head;
if(!a || !b)
return NULL;
// t1 points to the smallest number
if(a->n < b->n)
{
t1 = a;
t2 = b;
head = a;
}
else
{
t1=b;
t2=a;
head =b;
}
while(t1 && t2)
{
cout << t1 << " " << t2 << endl;
if(t1->next && (t1->next->n < t2->n))
{
t1 = t1->next; //move to next element in smaller list
}
else
{
list* t=t1->next;
list* k=t2->next;
t1->next = t2;
t2->next = t;
t2 = k;
t1 = t1->next;
}
}
return head;
}
No comments:
Post a Comment