别忘记断链哦!!!
核心思路:利用快慢指针找到分治中点,其余和数组的归并无异
单链表别带头节点
#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
typedef int Elemtype;
typedef struct LNode
{
Elemtype data;
struct LNode *next;
} LNode,*LinkList;
LinkList List_TailInsert(LinkList L)
{
int x;
L=(LinkList)malloc(sizeof(LinkList));
L->next=NULL;
LNode *r=L,*s;
scanf("%d",&x);
while(x!=9999)
{
s=(LNode*)malloc(sizeof(LNode*));
s->data=x;
r->next=s;
r=s;
scanf("%d",&x);
}
r->next=NULL;
return L->next;
}
void PrintLinkList(LinkList L)
{
printf("打印链表\n");
while(L!=NULL)
{
printf("%d--->",L->data);
L=L->next;
}
printf("\n");
}
LNode* Merge(LinkList left,LinkList right){
LinkList head=(LNode*)malloc(sizeof(LinkList));
LNode *p=head;
while(left!=NULL&&right!=NULL){
if(left->data<right->data){
p->next=left;
left=left->next;
}else{
p->next=right;
right=right->next;
}
p=p->next;
}
while(left!=NULL){
p->next=left;
left=left->next;
p=p->next;
}
while(right!=NULL){
p->next=right;
right=right->next;
p=p->next;
}
p->next=NULL;
return head->next;
}
LNode* split(LinkList head){
if(head==NULL||head->next==NULL)return head;
LNode *fast=head,*slow=head,*preSlow;
while(fast->next!=NULL){
fast=fast->next;
preSlow=slow;
slow=slow->next;
if(fast->next)fast=fast->next;
}
fast->next=NULL;
preSlow->next=NULL;
return slow;
}
LinkList MergeSort(LinkList L){
if(L==NULL||L->next==NULL)return L;
LNode *mid=split(L);
LNode *left=MergeSort(L);
LNode *right=MergeSort(mid);
return Merge(left,right);
}
int main()
{
LinkList L=(LNode*)malloc(sizeof(LNode));
L=List_TailInsert(L);
PrintLinkList(L);
L=MergeSort(L);
printf("排序后结果:\n");
PrintLinkList(L);
return 0;
}