下午第五题标准答案
#include<stdio.h>
#define NODE_NUM 10
struct node
{
char ch;
int weight;
int parent;
int lchild,rchild;
}Ht[NODE_NUM];
void init(void)
{
Ht[1].ch='a'; Ht[1].weight=2; Ht[1].parent=5; Ht[1].lchild=0; Ht[1].rchild=0;
Ht[2].ch='b'; Ht[2].weight=7; Ht[2].parent=7; Ht[2].lchild=0; Ht[2].rchild=0;
Ht[3].ch='c'; Ht[3].weight=4; Ht[3].parent=5; Ht[3].lchild=0; Ht[3].rchild=0;
Ht[4].ch='d'; Ht[4].weight=5; Ht[4].parent=6; Ht[4].lchild=0; Ht[4].rchild=0;
Ht[5].ch='x'; Ht[5].weight=6; Ht[5].parent=6; Ht[5].lchild=1; Ht[5].rchild=3;
Ht[6].ch='x'; Ht[6].weight=11; Ht[6].parent=7; Ht[6].lchild=4; Ht[6].rchild=5;
Ht[7].ch='x'; Ht[7].weight=18; Ht[7].parent=0; Ht[7].lchild=2; Ht[7].rchild=6;
}
char *Hc[]=
{
"xxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxx"
};
void LeafCode(int root, int n)
{
int i,p=root, cdlen=0;
char code[20];
//Hc=(char **)malloc((n+1)*sizeof(char *));
for(i=1;i<=p;++i)
Ht[i].weight=0;
while(p)
{
if(Ht[p].weight==0)
{
Ht[p].weight=1;
if(Ht[p].lchild!=0)
{
p=Ht[p].lchild;
code[cdlen++]='0';
}
else if(Ht[p].rchild==0)
{
//Hc[p]=(char *)malloc((cdlen+1)*sizeof(char));
code[cdlen]='\0';
strcpy(Hc[p],code);
printf("%s\n",code); //我加上的
}
}
else if(Ht[p].weight==1)
{
Ht[p].weight=2;
if(Ht[p].rchild!=0)
{
p=Ht[p].rchild;
code[cdlen++]='1';
}
}
else
{
Ht[p].weight=0;
p=Ht[p].parent;
cdlen--;
}
}
}
void Decode(char *buff, int root)
{
int pre=root,p;
while(*buff!='\0')
{
p=root;
while(p!=0)
{
pre=p;
if(*buff=='0')
p=Ht[p].lchild;
else
p=Ht[p].rchild;
buff++;
}
buff--;
printf("%c",Ht[pre].ch);
}
}
main()
{
init();
LeafCode(7,4);
printf("\n");
Decode("010110111",7);
printf("\n");
}
输出:
0
10
110
111
bdac
关于Hc分配内存的问题,如果照题目上的方法程序会coredump,所以我改掉了
以上程序在HP UNIX上编译运行