歸併兩路有序鏈表

/*
*歸併兩路鏈表
*/
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; 
 }
相關文章
相關標籤/搜索