赫夫曼编码程序(参考严蔚敏数据结构)

#include <iostream>
using namespace std;

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

typedef char **HuffmanCode;
typedef char *EachHuffcode;

void Select(HuffmanTree HT,int length,int &s1,int &s2)
{
 //s1 lowest,s2 lower
 unsigned int min = 5000;
 HuffmanTree  p = HT;
 int i;

 for(i = 1, ++p; i <= length ; ++i,++p)
 {
  if(p->weight < min && p->parent == 0)
  {
   min = p->weight;
   s1 = i;
  }
 }

 min = 5000;
 p = HT;
 //Get the second less weight
 for(i = 1, ++p; i <= length ; ++i,++p)
 {
  if(p->weight < min && p->parent == 0)
  {
   if( i == s1)//case s1,ignore
    continue;
   min = p->weight;
   s2 = i;
  }
 }

}
void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC, int *w,int n)
{
 if(n <= 1)
  return;

 int m = 2 * n - 1;
 HT = new HTNode[m + 1];//0 is not used

 HuffmanTree p = HT;
 int i;

 for( i = 1, ++p; i <= n; ++i,++p,++w)
 {
  p->weight = *w;//NOte: never use this *p = {*w,0,0,0,0},because *p has already been declared
  p->parent = p->lchild = p->rchild = 0;
 }

 for(; i <= m; ++i,++p)
  p->weight = p->parent = p->lchild = p->rchild = 0;

 int s1;
 int s2;

 for( i = n + 1; i <= m; ++i)
 {
  Select(HT,i-1,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 = new EachHuffcode[n+1];//0 is not used
 char *cd = new char[n];
 cd[n-1] = '/0';//the end of each char
 int start;

 for(int i = 1; i <= n ; ++i)
 {//get each huff code for h[1] to h[n]
  start = n -1;
  for(int c = i, int f = HT[i].parent; f != 0; c = f ,f = HT[f].parent)
   if(c == HT[f].lchild) cd[--start] = '0';
   else cd[--start] = '1';
   HC[i] = new char[n - start];//allocate memory for each HT
   strcpy(HC[i],&cd[start]);
 }
 delete []cd;//don't forget release memory
}

int main(int argc, char* argv[])
{
 HuffmanTree hftree = NULL;
 HuffmanCode hfcode = NULL;

 int weight[4] = {7,5,2,4};//four node's weight

 HuffmanCoding(hftree,hfcode,weight,4);

 EachHuffcode *p = hfcode;

 ++p;
 for (int i = 0; i < 4; ++i,++p)
 {
  cout<<*p<<endl;//show each huffman code by each line
 }

 for(int i = 1; i <=4; ++i)

delete hfcode[i];//release memory

 delete []hfcode;
 delete []hftree;

 return 0;
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值