设为首页 加入收藏

TOP

Huffman编码C实现
2014-11-23 21:31:47 来源: 作者: 【 】 浏览:21
Tags:Huffman 编码 实现

Huffman编码:根据Huffman树进行编码的,用到的数据结构是二叉树。


typedef int elemtype;
typedef struct
{
elemtype weight;
int parent,l_child,r_child;
} binarytree;


//2、构建最优二叉树
void CreateHuffman(int leafnum, binarytree *huffmantree)
{
//leafnum个叶子,决定nodenum个结点数
int nodenum=2*leafnum-1;
huffmantree=(binarytree *)malloc(nodenum*sizeof(binarytree)); //0号单元也使用

//leafnum个叶子,决定nodenum个结点数,也决定了(nodenum-1)个bit位编码
char *huffmancode;
huffmancode =(char *)malloc((nodenum-1)*sizeof(char));


//huffmantree的初始化:叶子结点data权值手动输入,非叶子默认值都为0
cout<<"请输入叶子权值:";
int i;
for(i=0;i {
if(i {
cin>>huffmantree[i].weight;
}
else
{
huffmantree[i].weight=0;
}
huffmantree[i].parent=huffmantree[i].l_child=huffmantree[i].r_child=0;
}


int j;
//j从leafnum开始,指的是包含了新建子树的结点编号
for(j=leafnum;j {
int w1=32767,w2=0; //存储最小权值;
int p=0,q=0; //存储最小权值的编号;


int k;
for(k=0;k {
if(huffmantree[k].parent==0) //判断结点是否使用
{
if(huffmantree[k].weight {
w2=w1;
q=p;
w1=huffmantree[k].weight;
p=k;

}
else if(huffmantree[k].weight {
w2=huffmantree[k].weight;
q=k;
}
}
}
//p对应左节点,编码为‘0’;q对应左节点,编码为‘1’;
huffmancode[p]='0';
huffmancode[q]='1';

huffmantree[j].weight =w1+w2;
huffmantree[j].l_child=p;
huffmantree[j].r_child=q;
huffmantree[p].parent=j;
huffmantree[q].parent=j;
}


//3、寻找从子节点到根节点的编码 HuffmanCoding(int n,binarytree *HuffmanTree)
//针对每一个叶子,从叶子到根方向寻找huffmancode
//每一个叶子,对应的编码长度codelength
const int maxsize=10;
char iscode[maxsize][maxsize];
int m;
for(m=0;m {
int n=0;
iscode[m][n]=huffmancode[m];
int parent=huffmantree[m].parent;
while(parent !=0)
{
iscode[m][++n]=huffmancode[parent];
parent=huffmantree[parent].parent;
};


int x;
cout<<"第"< for(x=0;x cout< cout< }
}


void main()
{
binarytree *T=0;
int leafnum;
printf("输入叶子数量n=\n");
cin>>leafnum;
CreateHuffman( leafnum, T);
while(1);
}


编译结果如下:


Huffman编码C实现


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Huffman编码与解码的实现 下一篇双链表&链表合并&多项式相加算法

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: