哈夫曼压缩解压缩 都很少看见翻翻看如我定时开机
源代码在线查看: 利用哈夫曼树编写的解压缩算法.cpp
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//构造哈夫曼树
struct HuffNode
{
int weight;
int parent,lchild,rchild;
};
struct HuffTree
{
HuffNode *buffer ;
int leafnumber;
};
int CreatHuffmanTree(HuffTree &T,int leafnumber,int *weight)
{
T.buffer=new HuffNode[2*leafnumber-1];
if(T.buffer==NULL) return 0;
T.leafnumber=leafnumber;
for (int i=0;i {
T.buffer[i].weight=weight[i];
T.buffer[i].parent=-1;
T.buffer[i].lchild=-1;
T.buffer[i].rchild=-1;
}
for (int n=leafnumber;n {
int m1=-1,m2=-1;
for (int j=0;j if(T.buffer[j].parent==-1)
{
if (m1==-1||T.buffer[j].weight {
m2=m1;
m1=j;
}
else if (m2==-1||T.buffer[j].weight {
m2=j;
}
}
T.buffer[n].parent=-1;
T.buffer[n].lchild=m1;
T.buffer[n].rchild=m2;
T.buffer[m1].parent=n;
T.buffer[m2].parent=n;
T.buffer[n].weight=T.buffer[m1].weight+T.buffer[m2].weight;
}
return 1;
}
//构造储存的码表
struct CodeNode
{
int *buffer;
int bufferlen; // bufferlen 表示编码的长度
int weight;
};
//统计各种字节频率
int Statistics(char *srcfilename,CodeNode *p)
{
FILE *fp;
if((fp=fopen(srcfilename,"rt"))==NULL)
return 0;
//初始化字节频率数组
for (int i=0;i p[i].weight=0;
int ch;
while ( (ch=fgetc(fp))!=EOF )
p[ch].weight++;
fclose( fp);
return 1;
}
//构造编码树
int CreateCode(char *srcfilename,CodeNode *Code ,HuffTree &T)
{
Statistics(srcfilename,Code);
int *Codeweight;
Codeweight =new int[256];
for (int i=0;i {
Codeweight[i]=Code[i].weight;
}
CreatHuffmanTree(T,256,Codeweight);
return 1;
}
//储存编码
int StoreCode(CodeNode *Code,HuffTree &T)
{ int k ; //k 作为记录编码的长度
stack S; //建立一个栈用于存储编码
for (int i=0;i {
int j=i;
k=0;
while(T.buffer[j].parent!=-1)
{
k=k+1;
if (T.buffer[T.buffer[j].parent].lchild==j)
S.push(0);
else
S.push(1);
j=T.buffer[j].parent;
}
Code[i].buffer=new int[k];
Code[i].bufferlen=k;
for (int m=0;m {
Code[i].buffer[m]=S.top();
S.pop();
}
}
return 1;
}