哈夫曼编码算法的实现

来源:百度知道 编辑:UC知道 时间:2024/06/15 03:30:54
基本要求:
1.任意性:用户输入任意的字符串,系统自动给出每个字符的哈夫曼编码和对应的哈夫曼树
2.友好性:界面要友好,输入有提示,尽量展示人性化
3.可读性:源程序代码清晰、有层次
4.健壮性:用户输入非法数据时,系统要及时给出警告信息

在网上看到一个,刚好用到,我试过的,正确
#include <stdio.h>
#include<malloc.h>
#include <string.h>
#include<fstream>
#include<iostream>
using namespace std;

typedef struct {
unsigned int weight;
char ch1;
unsigned int parent,lchild,rchild;
}HTNode,*HuffmanTree;

typedef char **HuffmanCode;

typedef struct {
char ch;
char code[7];
}codenode,*code;

void select(HuffmanTree HT,int n,int & s1,int &s2){ //从哈夫曼树中选择出最小的两个节点
for(int i=1;i<=n;i++)
if(!HT[i].parent){
s1=i; break;
}
for(i++;i<=n;i++)
if(!HT[i].parent){
s2=i; break;
}
if(HT[s1].weight-HT[s2].weight){
int temp; temp=s1; s1=s2; s2=temp;
}
for(i=1;i<=n;i++) //对数组进行遍历,寻找最小的两个节点
if(!HT[i].parent){
if(HT[i].weight<HT[s1].weight){
s2=s1; s1=i;
}
else if(HT[i].weight<HT[s2].weight&&i!=s1)