哈夫曼编码c++递归实现
#include <iostream>#include <queue>#include<algorithm>#include<string>using namespace std;struct Node{char c;int val;Node *r=NULL;Node *l=NULL;};struct tmp{int key;Node* node;b
·
#include <iostream>
#include <queue>
#include<algorithm>
#include<string>
using namespace std;
struct Node
{
char c;
int val;
Node *r=NULL;
Node *l=NULL;
};
struct tmp
{
int key;
Node* node;
bool operator < (const tmp &t) const
{
return key>t.key;
}
}temp;
int print_Haffman(Node* node,string str);
//需要修改的地方
int list_val[]={5,4,3,2,1};
char list_char[]={'A','B','C','D','E'};
int len=sizeof(list_val)/sizeof(list_val[0]);
int main(int argc, char** argv) {
Node list[len];
for (int i=0;i<len;i++)
{
list[i].c=list_char[i];
list[i].val=list_val[i];
}
priority_queue<tmp> que;//这个是优先队列,cpp泛值属实没搞懂
for (int i=0;i<len;i++)
{
temp.node=&list[i];
temp.key=list[i].val;
que.push(temp);
}
int i1=0;
Node list1[len];
while(que.size()!=1)
{
int val=0;
Node *tmpNode=&list1[i1];
tmpNode->l=que.top().node;
que.pop();
tmpNode->r=que.top().node;
que.pop();
tmpNode->val=tmpNode->r->val+tmpNode->l->val;
temp.key=tmpNode->val;
temp.node=tmpNode;
que.push(temp);
i1++;
}
print_Haffman(que.top().node,"");
return 0;
}
int print_Haffman(Node* node,string str)
{
if(!node->l)
{
cout<<node->c<<":"<<str<<endl;
return 0;
}
print_Haffman(node->l,str+"0");
print_Haffman(node->r,str+"1");
return 0;
}
更多推荐
已为社区贡献1条内容
所有评论(0)