问题遇到的现象和发生背景
哈夫曼编码函数有些问题,输出哈夫曼编码有些问题
用代码块功能插入代码,请勿粘贴截图
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct{
int weight;
int parent,lchild,rchild;
int flag;
}HTNode,*HuffmanTree;
typedef char** HuffmanCode;
void Select(HuffmanTree HT,int end,int *s1,int *s2){
int min=1,i;
for(i=1;i<=end;i++){
if(HT[i].flag!=0){
continue;
}
while(HT[min].flag!=0){
min++;
}
if(HT[i].parent==0&&HT[min].weight>HT[i].weight){
min=i;
}
}
*s1=min;
HT[min].flag=1;
min=1;
for(i=1;i<=end;i++){
if(HT[i].flag!=0){
continue;
}
while(HT[min].flag!=0){
min++;
}
if(HT[i].parent==0&&HT[min].weight>HT[i].weight){
min=i;
}
}
*s2=min;
HT[min].flag=1;
}
void CreateHuffmanTree(HuffmanTree *HT,int n){
if(n<=1) return;
int i,m=2*n-1;
*HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode));
HuffmanTree p=*HT;
for(i=1;i<=m;i++){
p[i].parent=0;
p[i].lchild=0;
p[i].rchild=0;
p[i].flag=0;
}
for(i=1;i<=n;i++){
puts("输入权值:");
scanf("%d",&(p[i].weight));
}
int s1,s2;
for(i=n+1;i<=m;i++){
Select(*HT,i-1,&s1,&s2);
p[s1].parent=p[s2].parent=i;
p[i].lchild=s1;
p[i].rchild=s2;
p[i].weight=p[s1].weight+p[s2].weight;
}
}
void CreateHuffmanCode(HuffmanTree HT,HuffmanCode *HC,int n){
int i;
(*HC)=(HuffmanCode)malloc((n+1)*sizeof(char *));
if(!(*HC)) printf("kong");
char *cd=(char *)malloc(n*sizeof(char));
if(!cd) printf("kong");
cd[n-1]='\0';
for(i=1;i<=n;i++){
int start=n-1;
int c=i;
int f=HT[i].parent;
while(f!=0){
--start;
if(HT[f].lchild==c){
cd[start]='0';
}else{
cd[start]='1';
}
c=f;
f=HT[f].parent;
}
//printf("%s",cd);
(*HC)[i]=(char *)malloc((n-start)*sizeof(char));
if(!(*HC)[i]) printf("kong");
strcpy((*HC)[i],cd+start);
printf("%s",HC[i]);
}
puts("--");
free(cd);
}
void printHuffmanTree(HuffmanTree HT,int n){
puts("节点\tweight\tparent\tlchild\trchild");
int i;
for(i=1;i<=n;i++){
printf("%d \t%d \t%d \t%d \t%d\n",i,HT[i].weight,HT[i].parent,HT[i].lchild,HT[i].rchild);
}
}
int main(int argc, char *argv[]) {
HuffmanTree HT;
HuffmanCode HC;
CreateHuffmanTree(&HT,8);
printHuffmanTree(HT,15);
puts("哈夫曼树");
CreateHuffmanCode(HT,&HC,8);
int i;
for(i=0;i<=8;i++){
printf("%s",HC[i]);
}
return 0;
}