添加注释版本:
/*
cout<<i<<endl<<" 结点 | data | weight | lchild | rchild | parent "<<endl;
for(int i=1;i<=m;++i)
{
cout<<i<<" | "<<HT[i].data<<" | "<<HT[i].weight<<" | "<<HT[i].lchild<<" | "<<HT[i].rchild<<" | "<<HT[i].parent<<endl;
}
*/
#include<iostream>
#include<stdio.h>
#include<string>
#include<cstring>
#include<algorithm>
#define MAX 0x3f3f3f3f
using namespace std;
typedef struct
{
char data;
int weight;
int parent;
int lchild;
int rchild;
bool tag;
}Huffnode,*HuffmanTree;
typedef struct
{
string *code;//存放字符的编码
char *data;//存放字符
int num;//存放一共有多少字符
}HuffmanCode;
void DisplayHuffmanCode(HuffmanCode &HC,int n)
{
for(int i=0;i<n;++i)
{
cout<<HC.code[i]<<endl;
}
}
void Select(HuffmanTree &HT,int index, int &s1, int &s2)
{
int min1=MAX;
int min2=MAX;
for(int i=1;i<=index;++i)
{
if(HT[i].parent==0&&HT[i].tag)
{
if(HT[i].weight<min1)
{
s1=i;
min1=HT[i].weight;
}
}
}
HT[s1].tag=0;//表明此节点已经被选中过
for(int i=1;i<=index;++i)
{
if(HT[i].parent==0&&HT[i].tag)
{
if(HT[i].weight<min2)
{
s2=i;
min2=HT[i].weight;
}
}
}
HT[s2].tag=0;
}
void CreatHuffmanTree(HuffmanTree &HT,int n)
{
/*n:待编码数有多少*/
if(n<=1)return;
int m=2*n-1; //计算节点个数
HT=new Huffnode[m+1];//0号单元未用,HT[m]表示根结点,从1开始存放数据
//初始化哈夫曼表
for(int i=1;i<=m;++i)
{
HT[i].lchild=0;
HT[i].rchild=0;
HT[i].parent=0;
HT[i].tag=1;
HT[i].data='