归并两路有序链表

/*
*归并两路链表
*/
template<typename elemType>
Node<elemType>* Mylist<elemType>::merge(Node<elemType> *first,Node<elemType> *second)
{//注意到这里链表first,second已经是顺序的了
  
Node<elemType> *resList=new Node<elemType>(); //开辟一个临时头节点 
Node<elemType> *current; 
current=resList; 
while(first!=NULL && second!=NULL)
{//某一条链表空时结束 
if((*cmp )(first->data,second->data))
{//根据函数指针来确定排序方式 
current->next=first; 
current=current->next; 
first=first->next; 
}
else
{ 
current->next=second; 
current=current->next; 
second=second->next; 
} 
}

//把还剩下不空的链表继续接到临时头结点所在的链表
while(first!=NULL)
{ 
current->next=first; 
current=current->next; 
first=first->next; 
} 
while(second!=NULL)
{ 
current->next=second; 
current=current->next; 
second=second->next; 
} 
current = resList->next;
delete resList;//记得释放头结点
return current; 
 }

 

posted @ 2014-02-11 17:29  桂皮猪  阅读(334)  评论(0编辑  收藏  举报