链表排序

504 篇文章 0 订阅
// merger_link2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"


// Link 排序.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

typedef struct node
{
	int value;
	struct node *next;
}
Node;

Node *mergeLink(Node* LinkA, Node* LinkB)
{
	if (LinkA == NULL && LinkB == NULL)
		return NULL;

	if (LinkA == NULL)
		return LinkB;
	else if (LinkB == NULL)
		return LinkA;

	Node *pNodeA = LinkA;
	Node *pNodeB = LinkB;
	Node *pNodeNewCur = NULL;
	Node *pNodeNewHead = NULL;

	if (pNodeA->value < pNodeB->value)
	{
		pNodeNewHead = pNodeNewCur = pNodeA;
		pNodeA = pNodeA->next;
	}
	else
	{
		pNodeNewHead = pNodeNewCur = pNodeB;
		pNodeB = pNodeB->next;
	}

	while (pNodeA && pNodeB)
	{
		if (pNodeB->value >= pNodeA->value)
		{
			pNodeNewCur->next = pNodeA;
			pNodeA = pNodeA->next;
		}
		else
		{
			pNodeNewCur->next = pNodeB;
			pNodeB = pNodeB->next;
		}
		pNodeNewCur = pNodeNewCur->next;
	}

	pNodeNewCur->next = (pNodeA == NULL) ? pNodeB:pNodeA;

	return pNodeNewHead;
}


Node* sortLink(Node *head)
{
	if (head == NULL)
		return head;

	if (head->next == NULL)
		return head;


	Node *pMiddle = head;
	Node *pCur    = head;

	while (pCur->next && pCur->next->next != NULL)
	{
		pMiddle = pMiddle->next;
		pCur    = pCur->next->next;
	}

	Node *pRearHead = pMiddle->next;
	pMiddle->next = NULL;

	Node *pFrontList = sortLink(head);
	Node *pRearList  = sortLink(pRearHead);

	Node *pMergeList = mergeLink(pFrontList, pRearList);

	return pMergeList;
}


Node* getLastNode(Node *head)
{
	if (head == NULL)
		return NULL;

	if (head->next == NULL)
		return head;

	Node *pCur = head;

	while (pCur->next)
	{
		pCur = pCur->next;
	}

	return pCur;
}


void printLink(Node *head)
{
	if (head == NULL)
		return;

	Node *pCur = head;

	while (pCur)
	{
		printf("%d->", pCur->value);
		pCur = pCur->next;
	}
	printf("NULL");

	return;

}
int _tmain(int argc, _TCHAR* argv[])
{
//  3->6->2->4->1->5->8->7->NULL;

	Node Node1;
	Node Node2;
	Node Node3;
	Node Node4;
	Node Node5;
	Node Node6;
	Node Node7;
	Node Node8;

	Node1.value = 1;
	Node1.next = &Node5;

	Node2.value = 2;
	Node2.next = &Node4;

	Node3.value = 3;
	Node3.next = &Node6;

	Node4.value = 4;
	Node4.next = &Node1;

	Node5.value = 5;
	Node5.next = &Node8;

	Node6.value = 6;
	Node6.next = &Node2;

	Node7.value = 7;
	Node7.next = NULL;

	Node8.value = 8;
	Node8.next = &Node7;

	printLink(&Node3);

	Node *pLastNode = getLastNode(&Node3);

	Node *pNewList = sortLink(&Node3);

	printf("\r\n");

	printLink(pNewList);
	

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值