Huffman编码优先队列实现

#include <iostream> #include <vector> #include <queue> #include <stdlib.h> #include <time.h> #define MAX_SIZE 26 using namespace std; struct stNode{ char ch; int frequence; stNode * left; stNode * right; }; struct CMP{ bool operator()(const stNode& a,const stNode& b) { return a.frequence>b.frequence; } }; priority_queue<stNode,vector<stNode>,CMP> minHeap; stNode * pHuffmanTree=NULL; stNode *pNode; stNode *temp1,*temp2; int nHuffmanCode[MAX_SIZE]={0}; int nCount=0; void Random() { srand((unsigned)time(NULL)); int i=0; char ch='a'; for (i=0;i<MAX_SIZE;i++) { stNode temp; temp.ch=ch++; temp.frequence=rand()%30; temp.left=temp.right=NULL; minHeap.push(temp); cout<<temp.ch<<'/t'<<temp.frequence<<endl; } cout<<endl; } /* Travel the huffman tree, to generate huffman code of each character */ void Travel(stNode * tree) { if (tree->ch!='0') { int i; for (i=0;i<nCount;i++) cout<<nHuffmanCode[i]; cout<<'/t'<<tree->ch<<endl; return; } if (tree->left!=NULL){ nHuffmanCode[nCount++]=0; Travel(tree->left); nCount--; } if (tree->right!=NULL){ nHuffmanCode[nCount++]=1; Travel(tree->right); nCount--; } } void HuffmanCoding() { for (int i=0;i<MAX_SIZE-1;i++) { pNode=new stNode; pNode->ch='0'; // stNode temp1; temp1=&minHeap.top(); pNode->left=new stNode; memcpy((stNode*)pNode->left,(stNode*)temp1,sizeof(stNode)); minHeap.pop(); // stNode temp2; temp2=&minHeap.top(); pNode->right=new stNode; memcpy((stNode*)pNode->right,(stNode*)temp2,sizeof(stNode)); minHeap.pop(); pNode->frequence=pNode->left->frequence+pNode->right->frequence; minHeap.push(*pNode); } pHuffmanTree=&minHeap.top(); } int main() { Random(); /* while (!minHeap.empty()) { stNode t; t=minHeap.top(); cout<<t.ch<<'/t'<<t.frequence<<endl; minHeap.pop(); } cout<<endl; */ HuffmanCoding(); cout<<pHuffmanTree->ch<<'/t'<<pHuffmanTree->frequence<<endl; Travel(pHuffmanTree); return 0; } 

你可能感兴趣的:(Huffman编码优先队列实现)