//1 此算法有一个缺陷
//2我原本打算用另一种结构,待我再研究研究
//3C++标准库提供了一种更为方便的结构,但我不会用,在研究研究,搞清楚了再来粘贴
//4先发表在这了
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
struct node
{
node():frequence(0),ID(' '),left(NULL),right(NULL){}
int frequence;
char ID;
node* left;
node* right;
};
int cnt;
node* array[26];
int code[10];
ifstream fin("C:\\data8.in");
ofstream fout("C:\\data8.out");
void Init()
{
char ch;
int freq;
cnt=0;
while(fin>>ch>>freq)
{
node* pnode=new node();
pnode->ID=ch;
pnode->frequence=freq;
array[cnt++]=pnode;
}
}
void sort()
{
for(int i=1;i<cnt;++i)
{
for(int j=i;j>0;--j)
{
if(array[j]->frequence>array[j-1]->frequence)
{
node* pnode=array[j];
array[j]=array[j-1];
array[j-1]=pnode;
}
}
}
}
void Huffman()
{
while(cnt>1)
{
sort();
node* pnode=new node();
node* xnode=array[cnt-1];
array[cnt-1]=NULL;
node* ynode=array[cnt-2];
pnode->left=xnode;
pnode->right=ynode;
pnode->frequence=xnode->frequence+ynode->frequence;
array[cnt-2]=pnode;
--cnt;
}
}
void print(node* node,int pos,char ID)
{
if(node->left==NULL)
{
fout<<node->ID<<":";
for(int i=0;i<pos;++i)
{
fout<<code[i];
}
fout<<endl;
return;
}
code[pos]=0;
print(node->left,pos+1,node->ID);
code[pos]=1;
print(node->right,pos+1,node->ID);
}
void DeleteNode(node* pnode)
{
if(pnode->left!=NULL)
{
DeleteNode(pnode->left);
DeleteNode(pnode->right);
delete pnode;
}
}
int main()
{
Init();
Huffman();
print(array[0],0,array[0]->ID);
DeleteNode(array[0]);
return 0;
}
Huffman Codes
最新推荐文章于 2021-01-31 19:03:18 发布