
今天没有时间跟你多解释了,下面是我以前写的程序,你应该灶清可以看得隐含前懂:
#include
#include
#include
#define N 27
#define M 100
#define Max 10000
typedef struct hufnode
{
char character;
int weight;
struct hufnode *lch;
struct hufnode *rch;
struct hufnode *prt;
int self;
int lchild;
int rchild;
int parant;
} ET;
ET *bh, *Temp[2*N-1];
void select(ET *p, int k, int *i, int *j)
{
int m, n=0;
while( (n
m = (p+n)->weight;
*i=n;
while(n
if( ((p+n)->weight
{
*i=n;
m = (p+n)->weight;
}
n=n+1;
}
n=0;
while( (n
m = (p+n)->weight;
*j=n;
while(n
if( ((p+n)->weight
{
*j=n;
m = (p+n)->weight;
}
n=n+1;
}
if( (*i)>(*j) ) { n=(*i); *i=(*j); *j=n; }
}
void HuffTree(char c[], int w[], int n, int m)
{
ET *p;
int k, i, j;
p = (ET *)malloc(m*sizeof(ET));
for(k=0; k
(p+k)->prt = NULL;
(p+k)->lch = NULL;
(p+k)->rch = NULL;
(p+k)->self = 100;
(p+k)->parant = -1;
(p+k)->lchild = -1;
(p+k)->rchild = -1;
if(k
(p+k)->character = c[k];
(p+k)->weight = w[k];
}
else
{
(p+k)->character = '?';
(p+k)->老正weight = Max;
}
}
for(k=n; k
select(p,k,&i,&j);
(p+i)->prt = (p+k);
(p+i)->parant = k;
(p+j)->prt = (p+k);
(p+j)->parant = k;
(p+k)->lch = (p+i);
(p+k)->lchild = i;
(p+k)->rch = (p+j);
(p+k)->rchild = j;
(p+k)->weight = (p+i)->weight+(p+j)->weight;
}
for(k=0; k
(p+k)->self = k;
Temp[k] = p+k;
}
bh=p+m-1;
}
void push(int s[], int *top, int x)
{
*top = *top+1;
s[*top-1] = x;
}
int pop(int s[], int *top, int *y)
{
*y = s[*top-1];
*top = *top-1;
return *y;
}
void HuffCode(ET *bt)
{
ET *r=bt, *q;
int t1=0, t2=0;
int s[N], x, *y=&t1, *top=&t2;
while(r!=bh)
{
q=r; r=r->prt;
if(r->lch == q)
{ x=0; push(s,top,x); }
else
{ x=1; push(s,top,x); }
}
while(*top!=0)
printf("%d", pop(s,top,y) );
}
void print(ET *Node)
{
if(Node->character!='?')
{
printf("结点编号:%2d 字符:%c 权:%4d 父结点:%2d 左子树:%2d 右子树:%2d ",
Node->self, Node->character, Node->weight, Node->parant, Node->lchild, Node->rchild);
if(Node->character!='?')
{
printf("编码:");
HuffCode(Node);
printf("\n");
}
else printf("非叶子结点\n");
}
}
void main()
{
int i, j;
char tempchr[M];
int wei[] = {186, 64, 13, 22, 32, 103, 21, 15, 47, 57, 1, 5, 32, 20, 57, 63, 15, 1, 48,
51, 80, 23, 8, 18, 1, 16, 1};
char chr[] = {' ', 'a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q',
'r','s','t','u','v','w','x','y','z'};
int n=N, m=2*n-1;
HuffTree(chr,wei,n,m);
for(i=0; i
printf("\n请输入字符串:");
i=0;
do tempchr[i++]=getchar();
while(tempchr[i-1]!='\n');
tempchr[i-1]='\0';
printf("该字符串编码为:\n");
for(i=0; tempchr[i]!='\0'; i++)
{
if(tempchr[i]!=' ' && (tempchr[i]<'a' || tempchr[i]>'z') ) {printf("?");continue;}
for(j=0; j
HuffCode(Temp[j]);
}
printf("\n\n");
}
你可扒圆模以规定左子树是腔明0,右子树是1嘛~~~这样从根到叶子就会得到一春缓串类似011101的串,这就是叶子编码了
define N 27
#define M 100
#define Max 10000