头文件:
/*基数排序,单链表实现*/
#ifndef RADIX_SORT_H
#define RADIX_SORT_H
#include
#define FLOWOVER -1
#define LIST_EMPTY -2
struct RadixSort;
typedef struct RadixSort * List;
typedef struct RadixSort * Node;
typedef int Element;
struct RadixSort
{
Element elem;
Node next;
};
List CreateList(void);//创建空表,返回表头地址
bool IsLast(Node N);//检测输入节点是否为表尾,是返回true
bool IsEmpty(List L);//检测输入表是否为空,是返回true
List DestroyList(List L);//删除表并释放内存
void AddNode(List L, Element e);//在表尾加入数据域为e的节点
void MoveNode(List L1, List L2);//将表L2中的头节点移动成为L1的尾节点
void PrintList(List L);//从第一个节点开始输出表中数据
#endif
实现文件:
#include
#include
#include
#include "radix_sort.h"
List CreateList(void)
{
List L;
L = (List)malloc(sizeof(struct RadixSort));
if(L == NULL)
exit(FLOWOVER);
L->next = NULL;
}
bool IsLast(Node N)
{
return N->next == NULL;
}
bool IsEmpty(List L)
{
return L->next == NULL;
}
List DestroyList(List L)
{
Node temp;//临时存储被free节点的后继
while(L != NULL){
temp = L->next;
free(L);
L = temp;
}
return NULL;//防止表头L成为野指针
}
void AddNode(List L, Element e)
{//新建节点添加在表尾
Node N;
N = (Node)malloc(sizeof(struct RadixSort));
if(N == NULL)
exit(FLOWOVER);
N->next = NULL;
N->elem = e;
while(!IsLast(L))
L = L->next;
L->next = N;
}
void MoveNode(List L1, List L2)
{//将表L2中的头节点移动成为L1的尾节点
Node temp;//用于临时存储L2表头地址
while(!IsLast(L1))
L1 = L1->next;//使L1指向L1表尾
if(L2->next == NULL)
exit(LIST_EMPTY);
temp = L2;
L2 = L2->next;
temp->next = L2->next;
L1->next = L2;
L2->next = NULL;
}
void PrintList(List L)
{
L = L->next;
while(L != NULL){
printf("%d ", L->elem);
L = L->next;
}
printf("\n");
}
测试文件:
#include
#include
#include "radix_sort.h"
int main()
{
List L[10], sortList;
int i, j, amount, tempE, firstE, tempSub;
sortList = CreateList();
for(i = 0; i < 10; i++)
L[i] = CreateList();
printf("输入要排序数字的总个数:");
scanf("%d", &amount);
printf("逐个输入需要排序的数:");
for(i = 0; i < amount; i++){
scanf("%d", &tempE);
AddNode(sortList, tempE);
}
for(i = 0; i < 3; i++){
while(!IsEmpty(sortList)){//单桶头->十桶尾
firstE = sortList->next->elem;//取出第一个节点的数据
tempSub = (int)(firstE / pow(10, i)) % 10;//依次取出个十百位数字
MoveNode(L[tempSub], sortList);
}
for(j = 0; j < 10; j++){//十桶头->单桶尾
while(!IsEmpty(L[j]))
MoveNode(sortList, L[j]);
}
printf("经过第%d轮排序,单桶中数据序列为:", i + 1);
PrintList(sortList);
}
return 0;
}