// 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;
}
链表排序
最新推荐文章于 2022-03-09 14:35:38 发布