#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
#define MAXE 20 // 线性表中最多的元素个数
#define MAXR 10 // 基数的最大取值
#define MAXD 8 // 关键字位数的最大取值
// 排序数据节点类型
typedef struct node
{
char data[MAXD];
struct node * next;
}RecType;
void CreateLink(RecType *&p, char *a[], int n);
void DispLink(RecType *p);
void RadixSort(RecType *&p, int r, int d)
{
// 用于分配和收集的队列
RecType *head[MAXR], *tail[MAXR], *t;
int i, j, k;
for(i = 0; i < d; ++ i)
{
// 初始化各链队首,尾指针
for(j = 0; j < r; ++ j)
{
head[j] = tail[j] = NULL;
}
// 分配每一个节点
while(p != NULL)
{
k = p->data[i] - '0';
if(head[k] == NULL)
{
head[k] = p;
tail[k] = p;
}
else
{
tail[k]->next = p;
tail[k] = p;
}
p = p->next;
}
// 再用p来收集所有节点
p = NULL;
for(j = 0; j < r; ++ j)
{
if(head[j] != NULL)
{
if(p == NULL)
{
p = head[j];
t = tail[j];
}
else
{
t->next = head[j];
t = tail[j];
}
}
}
t->next = NULL;
cout << "按" << i << "位排序 ";
DispLink(p);
}
}
void CreateLink(RecType *&p, char a[MAXE][MAXD], int n)
{
RecType *s, *t;
for(int i = 0; i < n; ++ i)
{
s = (RecType *)malloc(sizeof(RecType));
strcpy(s->data, a[i]);
if(i == 0)
{
p = s;
t = s;
}
else
{
t->next = s;
t = s;
}
}
t->next = NULL;
}
void DispLink(RecType *p)
{
while(p != NULL)
{
cout << p->data[1] << p->data[0] << " ";
p = p->next;
}
cout << endl;
}
int main()
{
int n = 10, r = 10, d = 2;
int i, j, k;
RecType *p;
char a[MAXE][MAXD];
int b[] = {75,23,98,44,57,12,29,64,38,82};
for(i = 0; i < n; ++ i)
{
k = b[i];
for(j = 0; j < d; ++ j)
{
a[i][j] = k % 10 + '0';
k = k / 10;
}
a[i][j] = ' ';
}
CreateLink(p, a, n);
cout << endl;
cout << "初始关键字 " << endl;
DispLink(p);
RadixSort(p, 10, 2);
cout << "最终结果 " << endl;
DispLink(p);
cout << endl;
return 0;
}