合并两个链表(c++)
输入的链表按照其元素从小到大的顺序排序,输出的链表也按从小到大的顺序排序,请合并两个链表
template<typename E>
Link<E> * LList<E>::mergeList(LList<E> * l1,LList<E>* l2)
{
Link<E> *list1=l1->head,*list2=l2->head;
//Make sure list1 and list2 are not empty
if(list1->next==NULL && list2->next==NULL) return (Link<E>*)0;
else if(list1->next==NULL) return list2;
else if (list2 ->next == NULL) return list1;
Link<E> *newList,* curr,* p,* q; //Temporary node
p=list1->next;
q=list2->next; //p,q points to the first node
newList=new Link<E>();
curr = newList;
//Traverse and compare the elements in list1 and list2 until one is empty
while(p!=NULL && q!=NULL){
//Find the smallest element and connect to newList, then iterate over the next element
if(p->element<=q->element){
curr->next=p;
p=p->next;
}else{
curr->next=q;
q=q->next;
}
curr =curr->next;
}
//Link the remaining elements of the comparison to the newList directly
curr->next=(q==NULL)?p:q;
return newList; //return the newList
}