算法思路:先将链表中的数据复制到数组中,再采用快速排序算法(时间复杂度为O(nlog2n)进行排序,然后将数组元素依次插入到链表中,以空间换时间。
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{//单链表结点结构体类型
ElemType data;//数据域
struct LNode *next;//指针域
}LNode,*LinkList;
//尾插法创建单链表(带头结点)
LinkList List_TailInsert(LinkList &L){
L = (LinkList)malloc(sizeof(LNode));
L -> next = NULL;
LNode *s,*r = L;//r指向尾结点
int x;
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;
}
//头插法创建单链表(带头结点)
LinkList List_HeadInsert(LinkList &L){
L = (LinkList)malloc(sizeof(LNode));
L -> next = NULL;
LNode *s;
int x;
scanf("%d",&x);
while(x != 9999){
s = (LNode*)malloc(sizeof(LNode));
s -> data = x;
s -> next = L -> next;
L -> next = s;
scanf("%d",&x);
}
return L;
}
void List_Print(LinkList L){
LNode *p = L -> next;
while(p != NULL){
printf("%d",p -> data);
p = p -> next;
}
}
int Partition(ElemType A[],int low,int high){//一趟划分
ElemType pivot = A[low];//将当前表中第一个元素设为枢轴,对表进行划分
while(low < high){ //循环跳出条件
while(low < high && A[high] > pivot)
--high;
A[low] = A[high]; //将比枢轴小的元素移动到左端
while(low < high && A[low] < pivot)
++low;
A[high] = A[low]; //将比枢轴大的元素移动到右端
}
A[low] = pivot; //枢轴元素存放到最终位置
return low; //返回存放枢轴的最终位置
}
void QuickSort(ElemType A[],int low,int high){
if(low < high){ //递归跳出的条件
//Partition()就是划分操作,将表A[low...high]划分为两个子表
int pivotpos = Partition(A,low,high);//划分
QuickSort(A,low,pivotpos - 1); //依次对两个子表进行递归排序
QuickSort(A,pivotpos + 1,high);
}
}
int main(){
LinkList L = NULL;
List_TailInsert(L);
//List_HeadInsert(L);
ElemType *arr = NULL;//动态分配一个数组
arr = (ElemType *)malloc(sizeof(ElemType));
LNode *p = L -> next;
int i = 0;
while(p != NULL){
arr[i++] = p -> data;
p = p -> next;
}
printf("排序前的单链表:");
List_Print(L);
QuickSort(arr,0,i-1);
int k = 0;
LNode *q = L -> next;
while(q != NULL){
q -> data = arr[k++];
q = q -> next;
}
printf("\n排序后的单链表:");
List_Print(L);
}
输出结果为: