时间复杂度O(nlogn),空间复杂度O(1)
#include<stdio.h>
#include <stdlib.h>
//定义链表
typedef struct ListNode
{
int data;
struct ListNode *next;
}linklist;
linklist *head = NULL;
//创建链表
linklist*CreateList(int *arr, int len)
{
linklist* p, *rear;
head = (linklist*)malloc(sizeof(linklist));
rear = head;
int count = 0;
while (count < len)
{
p = (linklist*)malloc(sizeof(linklist));
p->data = arr[count];
rear->next = p;
rear = p;
count++;
}
rear->next = NULL;
return head;
}
//打印链表
void ShowList(linklist* p)
{
printf("链表元素为:");
while (p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
//归并排序
linklist* MergeSortedList(linklist* h1, linklist* h2)
{
//返回的是链表指针,因为要递归调用
linklist* newhead;
//当有一个链表为空,则返回另外一个链表
if (h1 == NULL)
return h2;
if (h2 == NULL)
return h1;
//先找出链表头
if (h1->data <= h1->data)
{
newhead = h1;
h1 = h1->next;
}
else
{
newhead = h2;
h2 = h2->next;
}
linklist* temp = newhead;
//比较大小,并将链表排序
while (h1 && h2)
{
if (h1->data <= h2->data)
{
temp->next = h1;
temp = temp->next;
h1 = h1->next;
}
else
{
temp->next = h2;
temp = temp->next;
h2 = h2->next;
}
}
//如果其中一个链表还没排完,则把剩下的节点连接在已排好的链表即可
while (h1)
{
temp->next = h1;
temp = temp->next;
h1 = h1->next;
}
while (h2)
{
temp->next = h2;
temp = temp->next;
h2 = h2->next;
}
return newhead;
}
linklist *MergeSort(linklist *head)
{
//函数要有返回值,因为要递归下去
//头指针为空,则直接返回head
if (head == NULL || head->next == NULL)
return head;
linklist* fast = head;
linklist* slow = head;
//利用快指针是慢指针的两倍找到中间点
while (fast->next && fast->next->next)
{
fast = fast->next->next;
slow = slow->next;
}
linklist* lefthead = head;
linklist* righthead = slow->next;
//slow下一个节点必须是NULL,因为它是指向链表尾
slow->next = NULL;
//将左边、右边链表排好
lefthead = MergeSort(lefthead);
righthead = MergeSort(righthead);
//最后再返回合并后的链表
return MergeSortedList(lefthead, righthead);
}
//主函数
int main()
{
int array[] = { 1,3,5,7,9,2,4,6,8,10 };
CreateList(array, sizeof(array) / sizeof(array[0]));
ShowList(head->next);
linklist *head1 = MergeSort(head->next);
ShowList(head1);
return 0;
}