Struct ListNode
{
int data;
ListNode* next;
}
ListNode* GetMidNode(ListNode* list)
{
if(list==NULL)
return NULL;
ListNode* low=list;
ListNode* fast=list;
while(fast->next->next!=NULL)
{
low=low->next;
fast=fast->next->next;
}
return low;
}
//递归合并
ListNode* MergeList(ListNode* List1,ListNode* List2)
{
ListNode* pHead1=List1;
ListNode* pHead2=List2;
ListNode* pMergeHead;
if(List1==NULL && List2==NULL)
return NULL;
if(List1==NULL)
pMergeHead=List2;
if(List2==NULL)
pMergeHead=List1;
if(pHead1->data > pHead2->data)
{
pMergeHead=pHead2;
return MergeList(pHead1,pHead2->next);
}
else
{
pMergeHead=pHead1;
return MergeList(pHead1->next,pHead2);
}
}
//非递归合并
ListNode* MergeList(ListNode* List1,ListNode* List2)
{
ListNode* pHead1=List1;
ListNode* pHead2=List2;
ListNode* pMergeHead=NULL;
if(List1==NULL && List2==NULL)
return NULL;
if(List1==NULL)
pMergeHead=List2;
if(List2==NULL)
pMergeHead=List1;
if(pHead1->data > pHead2->data)
{
pMergeHead=pHead2;
pHead1=pHead1->next;
}
else
{
pMergeHead=pHead1;
pHead2=pHead2->next;
}
while(pHead1!=NULL && pHead2!=NULL)
{
if(pHead1->data<pHead2->data)
{
pMergeHead->next=pHead1;
pMergeHead=pMergeHead->next;
pHead1=pHead1->next;
}
else
{
pMergeHead->next=pHead2;
pMergeHead=pMergeHead->next;
pHead2=pHead2->next;
}
}
pMergeHead->next=pHead1?pHead1:pHead2;
return pMergeHead;
}
ListNode* MergeSort(ListNode* list)
{
if(list==NULL || list->next==NULL)
return NULL;
ListNode* pHead1=list;
ListNode* pHead2=GetMidNode(list);//获取中间结点,将链表分成两段
pHead1=MergeSort(pHead1);//对两段链表排序
pHead2=MergeSort(pHead2);
return MergeList(pHead1,pHead2);//合并两段链表
}
链表归并排序
最新推荐文章于 2024-09-30 18:44:26 发布