算法导论第十五章--霍夫曼编码

来源:互联网 发布:任盈盈 知乎 编辑:程序博客网 时间:2024/06/10 01:04

这道题纠结了一天,本想用简单点的方法实现,可是反而弄巧成拙。不过通过写该代码学会了如何使用优先级队列,对优先级队列有了进一步的了解。代码如下:

其中难度较大的是优先级队列的使用,详细的使用方法请参考博主的另一篇文章优先级队列的基本应用

//在优先级队列中存入指针类型的节点#include<iostream>#include<queue>#include<string>using namespace std;class Comapre;class Node{private:friend Comapre;int key;char ch;Node*left;Node*right;public:Node(int num,char c):key(num),ch(c),left(NULL),right(NULL){}//bool lessthan (const Node* node) const{return key>node->key;}int GetKey(){return key;}char GetChar(){return ch;}Node*GetLeft(){return left;}Node*GetRight(){return right;}void SetLeft(Node*node){this->left=node;}void SetRight(Node*node){this->right=node;}void SetChar(char a){ch=a;}void SetKey(int a){key=a;}};class Comapre{public://因为优先级队列中传递的指针,所以不能直接在Node类里重载比较运算符bool operator () (Node*node1,Node*node2){bool flag=node1->lessthan(node2);return flag;}};//使用优先级队列存储元素,优先级队列能保证队列最顶端的是按照键值key排列的最小的元素Node* Huffman(priority_queue<Node*,vector<Node*>,Comapre>que){//重复将最顶端的两个元素拿出合并之后再放入队列中while(que.size()>1){Node *node=new Node(0,0);node->SetLeft(que.top());que.pop();node->SetRight(que.top());que.pop();node->SetKey(node->GetLeft()->GetKey()+node->GetRight()->GetKey());que.push(node);}return que.top();}//利用中序遍历的方法输出霍夫曼编码//思路是每向左指一个节点st添加0,每向右指一个节点添加1,没迭代完一次要退出st最后一个元素//用到了string的pop_back函数void Inorder(Node* node,string st){if(node==NULL){return ;}else{if(node->GetLeft()!=NULL){st+='0';}Inorder(node->GetLeft(),st);if(node->GetLeft()==NULL&&node->GetRight()==NULL){cout<<node->GetChar()<<"'s code is :";for(int i=0;i<st.length();i++){cout<<st[i];}cout<<endl;}st.pop_back();if(node->GetRight()!=NULL)st+='1';Inorder(node->GetRight(),st);}}//将开辟的空间清空,不然会导致内存泄露void Delete(Node*node){if(node==NULL){return ;}Delete(node->GetLeft());Delete(node->GetRight());delete node;}int main(){string st;Node*n[6];n[0]=new Node(5,'f');n[1]=new Node(9,'e');n[2]=new Node(16,'d');n[3]=new Node(12,'c');n[4]=new Node(13,'b');n[5]=new Node(45,'a');priority_queue<Node*,vector<Node*>,Comapre>qu;int i;for(i=0;i<6;i++){qu.push(n[i]);}Node* R =Huffman(qu);Inorder(R,st);Delete(R);return 0;}


 

原创粉丝点击