数据结构C语言版赫夫曼树

来源:互联网 发布:没卡怎么在淘宝买东西 编辑:程序博客网 时间:2024/06/06 06:58
 /*自己编写的C语言的赫夫曼树*/
#include<stdio.h>#include<string.h>#define HUFFSIZE 8#define TOTALSIZE (2*HUFFSIZE) typedef struct {int weight;int parent;int leftchild;int rightchild;}HuffNode;typedef HuffNode HuffTree[TOTALSIZE];typedef struct{char ch;char code[HUFFSIZE + 1];}HuffCoding;typedef HuffCoding HuffCode[HUFFSIZE + 1 ];void Init_HuffTree(HuffTree ht, int a[]){memset(ht, 0, sizeof(HuffTree));for (int i = 1; i < HUFFSIZE + 1; ++i){ht[i].weight = a[i - 1];}}void Print_Hufftree(HuffTree ht)  {printf("%5s   %5s    %5s    %5s    %5s\n"," ID","weight","parent","leftchild","rightchild");for (int i = 1; i < TOTALSIZE ; ++i){printf("%5d    %5d    %5d    %5d    %5d\n", i, ht[i].weight, ht[i].parent, ht[i].leftchild, ht[i].rightchild);}}int find_min1(HuffTree ht,int n){int i = 1;while ((i < n)&&(ht[i].parent != 0))++i;for (int j = 1 + i; j < n; ++j){if((ht[j].parent==0)&&(ht[i].weight>ht[j].weight)){i = j;}}return i;}void find_min2(HuffTree ht, int n, int *min2){int min1;min1 = find_min1(ht, n);int i = 1;while (((i < n )&&(ht[i].parent != 0)) || (i==min1))++i;for (int j = 1 + i; j < n; ++j){if ((ht[j].parent == 0) && (ht[i].weight > ht[j].weight) &&( j!=min1)){i = j;}}*min2 = i;}void CreateHuffTree(HuffTree ht){int left, right;int k = HUFFSIZE + 1;while (k < TOTALSIZE){left=find_min1(ht, k);find_min2(ht, k, &right);ht[k].weight = ht[left].weight + ht[right].weight;ht[k].leftchild = left;ht[k].rightchild = right;ht[left].parent = k;ht[right].parent = k;++k;}}void Init_HuffCode(HuffCode hc,char br[]){memset(hc,0,sizeof(HuffCode));    for (int i = 1; i < HUFFSIZE + 1; ++i)   {hc[i].ch = br[i - 1];hc[i].code[0] = '\0';}}void CreateHuffCode(HuffTree ht, HuffCode hc){char code[HUFFSIZE + 1];int child, parent;for (int i = 1; i < HUFFSIZE + 1; ++i){int k=HUFFSIZE;code[k] = '\0';child = i;while ((parent=ht[child].parent) != 0){code[--k] = ht[parent].leftchild == child ? '0' : '1';child = parent;}strcpy_s(hc[i].code, &code[k]);}}void Print_Code(HuffCode hc){for (int i = 1; i < HUFFSIZE + 1; ++i){printf("%c的赫夫曼码:%s\n", hc[i].ch, hc[i].code);}}int main(){HuffTree ht;HuffCode hc;int a[] = { 1,2,23,4,5,6,7,8 };char br[] = { 'a','b','c','d','e','f','g','h' };Init_HuffTree(ht, a);Print_Hufftree(ht);CreateHuffTree(ht);Print_Hufftree(ht);Init_HuffCode(hc,br);CreateHuffCode(ht, hc);Print_Code(hc);getchar();return 0;}

原创粉丝点击