#include<iostream>
#include<vector>
using namespace std;
struct listNode
{
int data;
listNode *pNext;
};
listNode * mergeSortedList_0(listNode * pHead1,listNode *pHead2)
{
if(pHead1==NULL) return pHead2;
if(pHead2==NULL) return pHead1;
listNode *pNode1=pHead1,*pNode2=pHead2;
vector<listNode *> pNodeVector;
while(pNode1!=NULL && pNode2!=NULL)
{
if(pNode1->data < pNode2->data)
{
pNodeVector.push_back(pNode1);
pNode1=pNode1->pNext;
}
else
{
pNodeVector.push_back(pNode2);
pNode2=pNode2->pNext;
}
}
while(pNode1)
{
pNodeVector.push_back(pNode1);
pNode1=pNode1->pNext;
}
while(pNode2)
{
pNodeVector.push_back(pNode2);
pNode2=pNode2->pNext;
}
int i=0;
for(;i<pNodeVector.size()-1;i++)
{
pNodeVector[i]->pNext=pNodeVector[i+1];
}
pNodeVector[i]->pNext=NULL;
return pNodeVector[0];
}
listNode * mergeSortedList_1(listNode * pHead1,listNode *pHead2)
{
if(pHead1==NULL) return pHead2;
if(pHead2==NULL) return pHead1;
listNode *pNode1=pHead1,*pNode2=pHead2;
listNode *pHead=0;
if(pHead1->data < pHead2->data)
{
pHead=pHead1;
pNode1=pNode1->pNext;
}
else
{
pHead=pHead2;
pNode2=pNode2->pNext;
}
listNode *pTail=pHead;
while(pNode1 && pNode2)
{
if(pNode1->data < pNode2->data)
{
pTail->pNext=pNode1;
pTail=pNode1;
pNode1=pNode1->pNext;
}
else
{
pTail->pNext=pNode2;
pTail=pNode2;
pNode2=pNode2->pNext;
}
}
if(pNode1)
{
pTail->pNext=pNode1;
}
if(pNode2)
{
pTail->pNext=pNode2;
}
return pHead;
}
listNode * mergeSortedList_2(listNode *pHead1,listNode *pHead2)
{
if(pHead1==NULL) return pHead2;
if(pHead2==NULL) return pHead1;
listNode dummy;dummy.pNext=pHead1;dummy.data=-1;
listNode *pNode1=pHead1,*pNode2=pHead2;
listNode *pre=&dummy;
while(pNode1 && pNode2)
{
if(pNode1->data >=pNode2->data)
{
listNode *tmp2=pNode2->pNext;
pre->pNext=pNode2;
pNode2->pNext=pNode1;
pNode2=tmp2;
pre=pNode2;
}
else
{
pre=pNode1;
pNode1=pNode1->pNext;
}
}
if(pNode2)
{
pre->pNext=pNode2;
}
return dummy.pNext;
}
int main()
{
listNode n1,n2,n3,n4,n5,m1,m2,m3,m4;
n1.data=1,n2.data=3,n3.data=6,n4.data=10,n5.data=12;
m1.data=5,m2.data=7,m3.data=9,m4.data=13;
n1.pNext=&n2,n2.pNext=&n3,n3.pNext=&n4,n4.pNext=&n5,n5.pNext=NULL;
m1.pNext=&m2,m2.pNext=&m3,m3.pNext=&m4,m4.pNext=NULL;
listNode *pHead1=&n1,*pHead2=&m1;
listNode *pHead=mergeSortedList_2(pHead1,pHead2);
for(listNode *pNode=pHead;pNode!=NULL;pNode=pNode->pNext)
{
cout<<pNode->data<<endl;
}
return 0;
}
合并排序链表
最新推荐文章于 2022-10-11 18:00:52 发布