基数排序问题
/* Note:Your choice is C IDE */#include "stdio.h"
#include<malloc.h>
#define MAX 100
#define MAXR 10 /*基数的最大取值*/
#define MAXD 8 /*关键字位数的最大取值*/
typedef char *keytype;
typedef struct node
{
keytype data;
struct node *next;
}Rectype;
Rectype *creatlink(char *a[],int n)
{
int i;
Rectype *head,*p,*q;
p=head=(Rectype *)malloc(sizeof(Rectype));
if(n<1)return NULL;
for(i=0;i<n;i++)
{
q=(Rectype *)malloc(sizeof(Rectype));
q->data=a[i];
p->next=q;
p=q;
}
p->next=NULL;
return head;
}
Rectype *Radixsort(Rectype *head,int r,int d) /*r为基数,d为关键字位数*/
{
Rectype *front[MAXR],*rear[MAXR],*p,*q;
int i,j,k;
p=head->next;
for(i=d-1;i>=0;i--)
{
for(j=0;j<r;j++)
front[j]=rear[j]=NULL;
while(p)
{
k=p->data[i]-'0';
if(!front[k])
front[k]=p;
else
rear[k]->next=p;
rear[k]=p;
p=p->next;
}
for(j=0;j<r;j++)
if(front[j])
{
if(!p)
p=front[j];
else
q->next=front[j]; /*各链表首尾顺序链接*/
q=rear[j];
}
q->next=NULL;
}
head->next=p;
return head;
}
void display(Rectype *head)
{
Rectype *p;
p=head->next;
while(p)
{
printf("%6s",p->data);
p=p->next;
}printf("\n");
}
void main()
{
int n=10;
Rectype *head;
char *a[]={"75","23","98","44","57","12","29","64","38","82"};
printf("初始化关键字:");
head=creatlink(a,n);display(head);
printf("最终结果:");
Radixsort(head,10,2);display(head);
}
这里的 k=p->data[i]-'0';是什么意思,为什么要减零啊!
[[it] 本帖最后由 wangyinshiwo 于 2008-8-10 10:47 编辑 [/it]]