哈夫曼树编码 c语言感悟,哈夫曼树编码中的一些问题,求助

以下是全部代码

#include

#include

#include

#include

using namespace std;

#define LEN 8

typedef double DataType;

typedef struct

{

char ch;

int parent;

int LChild;

int RChild;

DataType weight;

}HNode,*Huffman;

typedef struct

{

int start;         //存放编码的起始位置(从高位向低位,从右向左)

int bit[LEN];      //存放huffman编码

}HCode,*HuffCode;

void createHuffmanTree(Huffman &h,int leaves,DataType *weight,char *ch)

{

int i,j;

int l=2*leaves-1;

h=(Huffman)malloc((l+1)*sizeof(HNode));

for(i=0;i

{

h[i].parent=-1;

h[i].LChild=-1;

h[i].RChild=-1;

h[i].weight=0;

h[i].ch=0;

}

for(i=0;i

{

h[i].weight=*(weight+i);

h[i].ch=*(ch+i);

}

for(i=0;i

{

DataType m1,m2;

int m1_pos,m2_pos;

m1=m2=65536;

m1_pos=m2_pos=0;

for(j=0;j

{

if(h[j].weight

{

m2=m1;

m1=h[j].weight;

m2_pos=m1_pos;

m1_pos=j;

}

else if(h[j].weight

{

m2=h[j].weight;

m2_pos=j;

}

}

h[leaves+i].parent=-1;

h[leaves+i].LChild=m1_pos;

h[leaves+i].RChild=m2_pos;

h[m1_pos].parent=leaves+i;

h[m2_pos].parent=leaves+i;

h[leaves+i].weight=m2+m1;

}

}

void huffmancode(Huffman &h,HuffCode &code,int leaves)

{

int i,j,p,c;

HCode hf;

char x[leaves][LEN];

code=(HuffCode)malloc((leaves)*sizeof (HCode));

for(i=0;i

{

c=i;

p=h[i].parent;

hf.start=LEN-1;

while(p!=-1){

if(h[p].LChild==c){

hf.bit[hf.start]=0;

}

else

{

hf.bit[hf.start]=1;

}

--hf.start;

c=p;

p=h[c].parent;

}

cout<

for(j=hf.start+1;j

code[i].bit[j]=hf.bit[j];

cout<

x[i][j]=code[i].bit[j]+'0';

cout<

}

cout<

code[i].start=hf.start+1;

}

for(int m=0;m

for(int n=0;n

cout<

for(int k=0;k

puts(x[k]);

}

void main(){

Huffman h;

HuffCode code;

int leaves;

cout<

cin>>leaves;

char ch[leaves];

cout<

for(int i=0;i

cin>>ch[i];

}

DataType weight[leaves];

cout<

for(int i=0;i

cin>>weight[i];

}

createHuffmanTree(h,leaves,weight,ch);

cout<

huffmancode(h,code,leaves);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值