两个有序链表合并——非递归实现

#include 
using namespace std;
#include      /* malloc, calloc, realloc, free */
struct ListNode{
	int value;
	ListNode* pNext;
};

ListNode* MergeList(ListNode* list1,ListNode* list2)
{
	if(list1==NULL)
		return list2;
	else if(list2==NULL)
		return list1;

	ListNode* pHead=NULL, *p=NULL,*p1=list1,*p2=list2;
	
	pHead=(list1->value>list2->value)?list2:list1;
	p=pHead;
	p1=pHead->pNext;
	p2=(list1->value>list2->value)?list1:list2;

	while(p1!=NULL&&p2!=NULL)
	{
		if(p1->valuevalue)
		{
			p->pNext=p1;
			p=p1;
			p1=p1->pNext;
		}
		else{
			p->pNext=p2;
			p=p2;
			p2=p2->pNext;
		}
	}
	if(p1!=NULL)
		p->pNext=p1;
	if(p2!=NULL)
		p->pNext=p2;
	return pHead;
}

ListNode* createList(int* a)
{
	ListNode* list=NULL,*preN=NULL;
	for(int i=0;i<4;i++)
	{
		ListNode* p=new ListNode();
		p->pNext=NULL;
		p->value=a[i];

		if(preN==NULL)
		{
			preN=p;
			list=p;
		}
		else
		{
			preN->pNext=p;
			preN=p;
		}
	}
	return list;
}
void deleteList(ListNode* list)
{
	while(list!=NULL)
	{
		ListNode* p=list->pNext;
		delete list;
		list=p;
	}
}
int main()
{
	int a[]={11,12,13,14};
	int b[]={5,6,10,11};

	ListNode* l1=createList(a);
	ListNode* l2=createList(b);

	ListNode* sortList=MergeList(l1,l2);
	ListNode* ptr=sortList;
	//ListNode* ptr=l2;
	while(ptr!=NULL)
	{
		cout<value<<"\t";
		ptr=ptr->pNext;
	}
	cout<

你可能感兴趣的:(C/C++)