資源簡介
哈夫曼編碼譯碼,數據結構課程設計,C++語言
代碼片段和文件信息
#include?
#include?
#include?
#include?
#include?
using?namespace?std;
#define?MAX?100
typedef?struct?HTNode{
char?c;
int?weight;
int?parentlchildrchild;
}HTNode*HuffmanTree;
typedef?char?**HuffmanCode;
HuffmanTree?HT;
HuffmanCode?HC;
void?Select(HuffmanTree?HTint?iint?&s1int?&s2)??//Select?sub-function
//choose?parent?is?0?and?weight?is?smallest?node?from?forest
{??int?jk=1;???????????????? //s1?is?the?least?of?HT[].weight
???while(HT[k].parent!=0) //s2?is?the?second?least?of?HT[].weight
???????k++;
???s1=k;
???for(j=1;j<=i;++j)
??????if(HT[j].parent==0&&HT[j].weight ??s1=j;
???k=1;
???while((HT[k].parent!=0||k==s1))
??????k++;
???s2=k;
???for(j=1;j<=i;++j)
??????if(HT[j].parent==0&&HT[j].weight ??s2=j;
}?//Select()?end
void?CreatHuffmanTree(HuffmanTree?&HT?int?n)
//creat?a?huffmantree?which?is?HT
{
int?s1??s2;
if(n?<=?1)?return?;
int?m?=?2?*?n?-?1;
HT?=?new?HTNode[m+1];
for(int?i?=?1;i?<=?m;++i)?{
HT[i].parent?=?0;?HT[i].lchild?=?0;?HT[i].rchild?=?0;
}
//read?char?and?weight?from?a?file
/*ifstream?infile(“data.txt“ios::in);
if(!infile)?{
cerr<<“open?error!“< exit(1);
}
for(int?i?=?1;i?<=?n;i++){
infile?>>HT[i].c>>?HT[i].weight;
}
infile.close();*/
cout?<“Enter?the?char?and?weight“< for(int?i?=?1;i?<=?n;i++){
cin?>>HT[i].c>>?HT[i].weight;
}
for(int?i?=?n+1;i?<=?m;++i)?{
Select(HTi-1s1s2);
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;
}
}
void?Savefile(HuffmanTree?HTint?n)
{
???//save?the?weight?into?a?file
ofstream?outfile(“datas.txt“ios::out);
if(!outfile)?{
cerr<<“open?error!“< exit(1);
}
for(int?i?=?1;i?<=?n;i++){
outfile< }
cout?<<“the?data?of?weight?is?already?saved?in?files“< outfile.close();
}
void?CreatHuffmanCode(HuffmanTree?HT?HuffmanCode?&HC?int?n)
//?Create?the?HuffmanCode
{
int?startcf;
HC?=?new?char*[n+1];
char?*cd?=?new?char[n];
cd[n-1]?=?‘\0‘;
cout< for?(int?i?=?1;i?<=?n;i++){
start?=?n-1;
c?=?i;?f?=?HT[i].parent;
while?(f?!=?0){
--start;
if(HT[f].lchild?==?c)?cd[start]?=?‘0‘;
else?cd[start]?=?‘1‘;
c?=?f;?f?=?HT[f].parent;
}
HC[i]?=?new?char[n?-?start];
strcpy(HC[i]&cd[start]);
cout?< cout?<“?‘s?Huffman?code?is:?“< }
delete?cd;
}
void?EnCod
- 上一篇:c++項目詳細簡單適合初學者
- 下一篇:英飛凌BMS解決方案C語言程序源碼及使用說明
評論
共有 條評論