合并排序链表

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值