声明:部分内容参考《数据结构》一书 已知一个文件中有8个不同的字符,个字符出现的个数分别是3,4,8,10,16,18,20,21.试为各字符编码,以节省存储空间。 详细请看源代码: #include <stdio.h> #include <stdlib.h> #include <string.h> #define NUM 8 const unsigned int n = NUM; const unsigned int m = 2*n - 1; typedef struct _HTNode { int weight; int parent; int lchild, rchild; }HTNode; void InitHTNode( HTNode t[] ) { int i; for( i=0; i < m; i++ ) { t[i].parent = -1; t[i].lchild = t[i].rchild = -1; t[i].weight = 0; } } //找出还未例如孩子节点中最小的两个值的对应数组下标 void HuffmanSelect( HTNode t[], int num, int &s1, int &s2 ) { int i; s1 = s2 = 0; t[s1].weight = 32767; for( i = 1; i <= num; i++ ) { if( t[i].weight != 0 && t[i].parent == -1 ) { if( t[i].weight < t[s1].weight ) { s2 = s1; s1 = i; } else if( t[i].weight < t[s2].weight ) s2 = i; } } } //建立哈夫曼树 void CreateHuffman( HTNode t[] ) { int i, s1, s2; for( i = n+1; i <= m; i++ ) { HuffmanSelect( t, i-1, s1, s2 ); t[s1].parent = i; t[s2].parent = i; t[i].lchild = t[s1].weight; t[i].rchild = t[s2].weight; t[i].weight = t[s1].weight + t[s2].weight; } } int main( void ) { HTNode t[m+1]; int i,d; InitHTNode(t); printf( "请输入权值: /n" ); for( i = 1; i <= n; i++ ) { scanf( "%d",&d ); t[i].weight = d; } //建立哈夫曼树 CreateHuffman( t ); return 0; }