单链表的排序(归并排序)


#include
using namespace std;
struct ListNode
{
	ListNode* pnext;
	int value;
	ListNode(int val):value(val),pnext(NULL)
	{
	}
};
ListNode* MergeList(ListNode* head1,ListNode* head2)
{
	if(head1==NULL)
		return head2;
	if(head2==NULL)
		return head1;
	ListNode* newHead=NULL,*end=NULL;
	if(head1->value>head2->value)
	{
		end=newHead=head2;
		head2=head2->pnext;
	}
	else
	{
		end=newHead=head1;
		head1=head1->pnext;
	}
	while(head1!=NULL&&head2!=NULL)
	{
		if(head1->value>head2->value)
		{
			end->pnext=head2;
			end=end->pnext;
			head2=head2->pnext;
		}
		else
		{
			end->pnext=head1;
			end=end->pnext;
			head1=head1->pnext;
		}
	}
	if(head1!=NULL)
	{
		end->pnext=head1;
	}
	if(head2!=NULL)
	{
		end->pnext=head2;
	}
	return newHead;
}
ListNode* MergeSort(ListNode* head)
{
	if(head==NULL)
		return NULL;
	ListNode* newHead,*pslow,*pfast;
	newHead=pslow=pfast=head;
	while(pfast->pnext!=NULL&&pfast->pnext->pnext!=NULL)
	{
		pslow=pslow->pnext;
		pfast=pfast->pnext->pnext;
	}
	if(pslow->pnext==NULL)//如果pslow的pnext为NULL说明仅有一个节点
	{
		return pslow;
	}
	pfast=pslow->pnext;
	pslow->pnext=NULL;
	pslow=newHead;
	newHead=MergeList(MergeSort(pslow),MergeSort(pfast));
	return newHead;
}

void PrintListNode(ListNode* head)
{
	while(head!=NULL)
	{
		cout<value<<" ";
		head=head->pnext;
	}
	cout<pnext=pnode2;
	pnode2->pnext=pnode3;
	pnode3->pnext=pnode4;
	pnode4->pnext=pnode5;
	pnode5->pnext=pnode6;
	pnode6->pnext=pnode7;
	pnode7->pnext=pnode8;
	pnode8->pnext=pnode9;


	PrintListNode(pnode1);
	ListNode*result=MergeSort(pnode1);
	PrintListNode(result);

}

你可能感兴趣的:(面试题集合)