基数排序链表c语言,基数排序单链表实现(C语言)

头文件:

/*基数排序,单链表实现*/

#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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值