霍夫曼树的编码与解码(c语言版)

#include <stdlib.h>
#include <stdio.h>
#include <strings.h>

#define MAXBIT      100
#define MAXVALUE  10000

typedef struct {
    int weight;
    int parent, lchild, rchild;
    char info;
}NTNode,*HuffmanTree;

typedef struct{
    int bit[MAXBIT];
    //再设置一个start用于表示编码在数组中的起始位置
    int start;
}HCodeType,*Hcode;

//创建霍夫曼树
HuffmanTree CreateHT(HuffmanTree HuffNode,int n,char a[],int weight[]){
    if(!(HuffNode =(HuffmanTree)malloc((2*n-1)*sizeof(NTNode))))printf("分配空间失败");
    int i,j,x1,x2,m1,m2;
    for(i=0;i<(2*n-1);i++){
        HuffNode[i].parent = -1;
        HuffNode[i].weight = -1;
        HuffNode[i].lchild = -1;
        HuffNode[i].rchild = -1;
    }
    //输入n个叶子节点的权值
    for(i=0;i<n;i++){
        HuffNode[i].weight = weight[i];
        HuffNode[i].info = a[i];
    }
    //构建树,生成霍夫曼树得循环n-1次,相当于实现select的部分
    for(i=0;i<n-1;i++){
        m1=m2=MAXVALUE;//m1始终是最小值,m2是次小值
        x1=x2=0;
        //找出所有节点中权值最小且没有父节点的根合成树
        for(j=0;j<n+i;j++){
            if(HuffNode[j].parent==-1&&HuffNode[j].weight<m1){
                m2 = m1;
                x2 = x1;
                m1 = HuffNode[j].weight;
                x1 = j;
            }else if(HuffNode[j].weight<m2&&HuffNode[j].parent==-1){
                m2 = HuffNode[j].weight;
                x2 = j;
            }
        }
        //设置找到的两节点新产生节点的信息
        HuffNode[n+i].weight = HuffNode[x1].weight + HuffNode[x2].weight;
        HuffNode[n+i].lchild = x1;
        HuffNode[n+i].rchild = x2;
        HuffNode[x1].parent = n+i;
        HuffNode[x2].parent = n+i;
    }
    return HuffNode;
}

void CreateHuffCode(HuffmanTree HuffNode,Hcode HuffCode,char a[],int n){
    HCodeType cd;//cd用来临时存储信息
    HuffCode = (HCodeType*)malloc((2*n-1)*sizeof(HCodeType));
    int i,j,c,p;
    for(i=0;i<n;i++){
        cd.start=n-1;//编码在bit数组中的开始存储位置,数组最大下标为n-1,霍夫曼树编码是从根到叶子的编码。我们从叶子节点开始所以需要倒着存。
        c=i;
        p = HuffNode[c].parent;
        while(p!=-1){
            if(HuffNode[p].lchild==c)
                cd.bit[cd.start]=0;//若叶子为双亲的左节点则编码0
            else
                cd.bit[cd.start]=1;//若叶子为双亲的右节点则编码1
            cd.start--;//最后一次运行时start指向存储编码的前一位
            c=p;
            p=HuffNode[c].parent;
        }
        for(j=cd.start+1;j<n;j++)
            HuffCode[i].bit[j]=cd.bit[j];
        HuffCode[i].start=cd.start + 1;//记录编码在数组中开始的位置
    }
    //输出已经保存好的霍夫曼编码
    for (i=0;i<n;i++)
        {
            printf ("%c's Huffman code is:",a[i]);
            for (j=HuffCode[i].start; j < n; j++){
                printf ("%d", HuffCode[i].bit[j]);
            }
            printf ("\n");
        }
}


void decoding(char a[],HuffmanTree T,int num){
    //num为叶子节点数,ch[]用于存放解码之后的字符,a[]存放要解码的01串
    int j=0,p=0;
    char ch[100];
    int i=0;
    while(i<strlen(a)){
        p = 2*num-2;
        while(T[p].lchild != -1){
            if(a[i]=='0'){
                p = T[p].lchild;
            }else{
                p = T[p].rchild;
            }
            i++;
        }
        ch[j] = T[p].info;
        j++;
    }
    ch[j] = '\0';
    for(int m=0;m<j;m++){
        printf("%c",ch[m]);
    }
    printf("\n");
}

int main(){
    HuffmanTree T;
    T = NULL;
    Hcode M;
    M = NULL;
    char a[] = {'a','b','c','d','e','f','\0'};//n=6
    int weight[] = { 5, 9, 12, 13, 16, 45 };
    char c[] = "011110110011011100";
    T = CreateHT(T, 6, a, weight);
    for(int n=0;n<6;n++){
        printf("%c",T[n].info);
    }
    printf("\n");
    CreateHuffCode(T,M,a,6);
    decoding(c,T,6);
    
}

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
#include #include #include #include using namespace std; # define MaxN 100//初始设定的最大结点数 # define MaxC 1000//最大编码长度 # define ImpossibleWeight 10000//结点不可能达到的权值 # define n 26//字符集的个数 //-----------哈夫曼树的结点结构类型定义----------- typedef struct //定义哈夫曼树各结点 { int weight;//权值 int parent;//双亲结点下标 int lchild;//左孩子结点下标 int rchild;//右孩子结点下标 }HTNode,*HuffmanTree;//动态分配数组存储哈夫曼树 typedef char**HuffmanCode;//动态分配数组存储哈夫曼编码表 //-------全局变量-------- HuffmanTree HT; HuffmanCode HC; int *w;//权值数组 //const int n=26;//字符集的个数 char *info;//字符值数组 int flag=0;//初始化标记 //********************************************************************** //初始化函数 //函数功能: 从终端读入字符集大小n , 以及n个字符和n个权值,建立哈夫曼树,并将它存于文件hfmTree中 //函数参数: //向量HT的前n个分量表示叶子结点,最后一个分量表示根结点,各字符的编码长度不等,所以按实际长度动态分配空间 void Select(HuffmanTree t,int i,int &s1,int &s2) { //s1为最小的两个值中序号最小的那个 int j; int k=ImpossibleWeight;//k的初值为不可能达到的最大权值 for(j=1;j<=i;j++) { if(t[j].weight<k&&t[j].parent==0) {k=t[j].weight; s1=j;} } t[s1].parent=1; k=ImpossibleWeight; for(j=1;j<=i;j++) { if(t[j].weight0),构造哈夫曼树HT,并求出n个字符的哈弗曼编码HC { int i,m,c,s1,s2,start,f; HuffmanTree p; char* cd; if(num<=1) return; m=2*num-1;//m为结点数,一棵有n个叶子结点的哈夫曼树共有2n-1个结点,可以存储在一个大小为2n-1的一维数组中 HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode));//0号单元未用 //--------初始化哈弗曼树------- for(p=HT+1,i=1;iweight=*w; p->parent=0; p->lchild=0; p->rchild=0; } for(i=num+1;iweight=0; p->parent=0; p->lchild=0; p->rchild=0; } //--------建哈夫曼树------------- for(i=num+1;i<=m;i++) { Select(HT,i-1,s1,s2);//在HT[1...i-1]选择parent为0且weight最小的两个结点,其序号分别为s1和s2 HT[s1].parent=i; HT[s2].parent=i; HT[i].lchild=s1; HT[i].rchild=s2;//左孩子权值小,右孩子权值大 HT[i].weight=HT[s1].weight+HT[s2].weight; } //-------从叶子到根逆向求每个字符的哈弗曼编码-------- HC=(HuffmanCode)malloc((num+1)*sizeof(char *));//指针数组:分配n个字符编码的头指针向量 cd=(char*)malloc(n*sizeof(char*));//分配求编码的工作空间 cd[n-1]='\0';//编码结束符 for(i=1;i<=n;i++)//逐个字符求哈弗曼编码 { start=n-1;//编码结束符位置 for(c=i,f=HT[i].parent;f!=0;c=f,f=HT[f].parent)//从叶子到跟逆向求哈弗曼编码 if(HT[f].lchild==c) cd[--start]='0';//判断是左孩子还是右孩子(左为0右为1) else cd[--start]='1'; HC[i]=(char*)malloc((num-start)*sizeof(char*));//按所需长度分配空间 int j,h; strcpy(HC[i],&cd[start]); } free(cd); } //****************初始化函数****************** void Initialization() { flag=1;//标记为已初始化 int i; w=(int*)malloc(n*sizeof(int));//为26个字符权值分配空间 info=(char*)malloc(n*sizeof(char));//为26个字符分配空间 ifstream infile("ABC.txt",ios::in); if(!infile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;i>info[i]; infile>>w[i]; } infile.close(); cout<<"读入字符成功!"<<endl; HuffmanCoding(HT,HC,w,n); //------------打印编码----------- cout<<"依次显示各个字符的值,权值或频度,编码如下"<<endl; cout<<"字符"<<setw(6)<<"权值"<<setw(11)<<"编码"<<endl; for(i=0;i<n;i++) { cout<<setw(3)<<info[i]; cout<<setw(6)<<w[i]<<setw(12)<<HC[i+1]<<endl; } //---------将建好的哈夫曼树写入文件------------ cout<<"下面将哈夫曼树写入文件"<<endl; ofstream outfile("hfmTree.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;i<n;i++,w++) { outfile<<info[i]<<" "; outfile<<w[i]<<" "; outfile<<HC[i+1]<<" "; } outfile.close(); cout<<"已经将字符与对应的权值,编码写入根目录下文件hfmTree.txt"<<endl; } //*****************输入待编码字符函数************************* void Input() { char string[100]; ofstream outfile("ToBeTran.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } cout<<"请输入你想要编码的字符串(字符个数应小于100),以#结束"<>string; for(int i=0;string[i]!='\0';i++) { if(string[i]=='\0') break; outfile<<string[i]; } cout<<"获取报文成功"<<endl; outfile.close(); cout<<"------"<<"已经将报文存入根目录下的ToBeTran.txt文件"<<endl; } //******************编码函数**************** void Encoding() { int i,j; char*string; string=(char*)malloc(MaxN*sizeof(char)); cout<<"下面对根目录下的ToBeTran.txt文件中的字符进行编码"<<endl; ifstream infile("ToBeTran.txt",ios::in); if(!infile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;i>string[i]; } for(i=0;i<100;i++) if(string[i]!='#') cout<<string[i]; else break; infile.close(); ofstream outfile("CodeFile.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;string[i]!='#';i++) { for(j=0;j<n;j++) { if(string[i]==info[j]) outfile<<HC[j+1]; } } outfile<<'#'; outfile.close(); free(string); cout<<"编码完成------"; cout<<"编码已写入根目录下的文件CodeFile.txt中"<<endl; } //******************译码函数**************** void Decoding() { int j=0,i; char *code; code=(char*)malloc(MaxC*sizeof(char)); char*string; string=(char*)malloc(MaxN*sizeof(char)); cout<<"下面对根目录下的CodeFile.txt文件中的代码进行译码"<<endl; ifstream infile("CodeFile.txt",ios::in); if(!infile) { cerr<<"打开失败"<<endl; exit(1); } for( i=0;i>code[i]; if(code[i]!='#') { cout<<code[i]; } else break; } infile.close(); int m=2*n-1; for(i=0;code[i-1]!='#';i++) { if(HT[m].lchild==0) { string[j]=info[m-1]; j++; m=2*n-1; i--; } else if(code[i]=='1') m=HT[m].rchild; else if(code[i]=='0') m=HT[m].lchild; } string[j]='#'; ofstream outfile("TextFile.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } cout<<"的译码为------"<<endl; for( i=0;string[i]!='#';i++) { outfile<<string[i]; cout<<string[i]; } outfile<<'#'; outfile.close(); cout<<"------译码完成------"<<endl; cout<<"译码结果已写入根目录下的文件TextFile.txt中"<<endl; free(code); free(string); } //*************打印编码函数**************** void Code_printing() { int i; char *code; code=(char*)malloc(MaxC*sizeof(char)); cout<<"下面打印根目录下文件CodeFile.txt中的编码"<<endl; ifstream infile("CodeFile.txt",ios::in); if(!infile) { cerr<<"打开失败"<<endl; exit(1); } for( i=0;i>code[i]; if(code[i]!='#') cout<<code[i]; else break; } infile.close(); cout<<endl; ofstream outfile("CodePrin.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;code[i]!='#';i++) { outfile<<code[i]; } outfile.close(); free(code); cout<<"------打印结束------"<<endl; cout<<"该字符形式的编码文件已写入文件CodePrin.txt中"<<endl; } //*************打印哈夫曼树函数**************** int numb=0; void coprint(HuffmanTree start,HuffmanTree HT) //start=ht+26这是一个递归算法 { if(start!=HT) { ofstream outfile("TreePrint.txt",ios::out); if(!outfile) { cerr<<"打开失败"<rchild,HT); //递归先序遍历 cout<<setw(5*numb)<weight<rchild==0) cout<<info[start-HT-1]<<endl; outfile<weight; coprint(HT+start->lchild,HT); numb--; outfile.close(); } } void Tree_printing(HuffmanTree HT,int num) { HuffmanTree p; p=HT+2*num-1; //p=HT+26 cout<<"下面打印赫夫曼树"<<endl; coprint(p,HT); //p=HT+26 cout<<"打印工作结束"<<endl; } //*************主函数************************** int main() { char choice; do{ cout<<"************哈弗曼编/译码器系统***************"<<endl; cout<<"请选择您所需功能:"<<endl; cout<<":初始化哈弗曼树"<<endl; cout<<":输入待编码字符串"<<endl; cout<<":利用已建好的哈夫曼树进行编码"<<endl; cout<<":利用已建好的哈夫曼树进行译码"<<endl; cout<<":打印代码文件"<<endl; cout<<":打印哈夫曼树"<<endl; cout<<":退出"<<endl; if(flag==0) { cout<<"请先初始化哈夫曼树,输入I"<<endl; cout<<""<>choice; switch(choice) { case 'I':Initialization();break; case 'W':Input();break; case 'E':Encoding();break; case 'D':Decoding();break; case 'P':Code_printing();break; case 'T':Tree_printing(HT,n);break; case 'Q':;break; default:cout<<"输入的命令出错,请重新输入!"<<endl; } }while(choice!='Q'); free(w); free(info); free(HT); free(HC); system("pause"); return 0; }
以下是一个简单的霍夫曼树C语言实现,包括创建霍夫曼树编码解码等功能: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 100 // 霍夫曼树节点 typedef struct node { char ch; int freq; struct node *left, *right; } Node; // 霍夫曼编码表 typedef struct code { char ch; char bits[MAX]; } Code; // 创建霍夫曼树 Node *createHuffmanTree(char *str) { int len = strlen(str); int freq[256] = {0}; for (int i = 0; i < len; i++) { freq[str[i]]++; } Node *nodes[256]; int n = 0; for (int i = 0; i < 256; i++) { if (freq[i] > 0) { nodes[n] = (Node *) malloc(sizeof(Node)); nodes[n]->ch = (char) i; nodes[n]->freq = freq[i]; nodes[n]->left = NULL; nodes[n]->right = NULL; n++; } } while (n > 1) { int i1 = 0, i2 = 1; if (nodes[i1]->freq > nodes[i2]->freq) { int tmp = i1; i1 = i2; i2 = tmp; } for (int i = 2; i < n; i++) { if (nodes[i]->freq < nodes[i1]->freq) { i2 = i1; i1 = i; } else if (nodes[i]->freq < nodes[i2]->freq) { i2 = i; } } Node *newNode = (Node *) malloc(sizeof(Node)); newNode->ch = '\0'; newNode->freq = nodes[i1]->freq + nodes[i2]->freq; newNode->left = nodes[i1]; newNode->right = nodes[i2]; if (i1 < i2) { for (int i = i2; i < n - 1; i++) { nodes[i] = nodes[i + 1]; } } for (int i = i1; i < n - 1; i++) { nodes[i] = nodes[i + 1]; } nodes[n - 2] = newNode; n--; } return nodes[0]; } // 生成霍夫曼编码表 void generateHuffmanCode(Node *root, Code *codes, char *bits, int depth) { if (root->left == NULL && root->right == NULL) { for (int i = 0; i < strlen(bits); i++) { codes[(int) root->ch].bits[i] = bits[i]; } codes[(int) root->ch].ch = root->ch; return; } bits[depth] = '0'; generateHuffmanCode(root->left, codes, bits, depth + 1); bits[depth] = '1'; generateHuffmanCode(root->right, codes, bits, depth + 1); } // 霍夫曼编码 void huffmanEncode(char *str, char *code) { Node *root = createHuffmanTree(str); Code codes[256]; char bits[MAX] = {'\0'}; generateHuffmanCode(root, codes, bits, 0); int len = strlen(str); int pos = 0; for (int i = 0; i < len; i++) { for (int j = 0; j < strlen(codes[(int) str[i]].bits); j++) { code[pos++] = codes[(int) str[i]].bits[j]; } } } // 霍夫曼解码 void huffmanDecode(char *code, char *str) { Node *root = createHuffmanTree(str); int len = strlen(code); Node *p = root; int pos = 0; while (pos < len) { if (code[pos] == '0') { p = p->left; } else { p = p->right; } if (p->left == NULL && p->right == NULL) { str[strlen(str)] = p->ch; p = root; } pos++; } } int main() { char str[MAX] = "Hello, World!"; char code[MAX] = {'\0'}; huffmanEncode(str, code); printf("%s\n", code); char str2[MAX] = {'\0'}; huffmanDecode(code, str2); printf("%s", str2); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值