/* * ===================================================================================== * * Filename: haffman.c * * Description: huffman coder decoder * * Version: 1.0 * Created: * Revision: none * Compiler: gcc * * * ===================================================================================== */ #include <unistd.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #define N 256 #define Maxsize 80 #define SOME 1 #define Empty 0 #define FULL -1 typedef unsigned long int WeightType; typedef unsigned char MyType; typedef struct //哈夫曼树 { MyType ch; //存字符 WeightType weight; /* 用来存放各个结点的权值 */ int parent, LChild, RChild; /*指向双亲、孩子结点的指针 */ } HTNode; typedef struct //队列 { int tag; int front; int rear; MyType length; char elem[Maxsize]; } SeqQueue; void writeFile(); void printHFM(HTNode * ht, int n); void code(char **hc, int n, unsigned char *ch); int InitQueue(SeqQueue * Q) { if (!Q) return 1; Q->tag = Empty; Q->front = Q->rear = 0; Q->length = 0; return 0; } int In_seqQueue(SeqQueue * Q, char x) { if (Q->front == Q->rear && Q->tag == SOME) return FULL; //full Q->elem[Q->rear] = x; // printf("in = %c",x); Q->rear = (Q->rear + 1) % Maxsize; Q->length++; Q->tag = SOME; return SOME; } int Out_Queue(SeqQueue * Q, char *x) { if (Q->tag == Empty) return Empty; *x = Q->elem[Q->front]; Q->length--; Q->front = (Q->front + 1) % Maxsize; if (Q->front == Q->rear) Q->tag = Empty; return SOME; } /* ------------------以上是队列的操作------------------------- */ void SelectMinTree(HTNode * ht, int n, int *k) { int i, temp; WeightType min; // printf(" Selecting……n= %d",n); for (i = 0; i <= n; i++) { if (0 == ht[i].parent) { min = ht[i].weight; //init min temp = i; break; } } for (i++; i <= n; i++) { if (0 == ht[i].parent && ht[i].weight < min) { min = ht[i].weight; temp = i; } } *k = temp; } // 对哈夫曼树排序,并统计叶子数量 int SortTree(HTNode * ht) { short i, j; HTNode tmp; for (i = N - 1; i >= 0; i--) { for (j = 0; j < i; j++) if (ht[j].weight < ht[j + 1].weight) { tmp = ht[j]; ht[j] = ht[j + 1]; ht[j + 1] = tmp; } } for (i = 0; i < N; i++) if (0 == ht[i].weight) return i; return i; //返回叶子个数 } //求哈夫曼0-1字符编码表 char **CrtHuffmanCode(HTNode * ht, short LeafNum) /*从叶子结点到根,逆向求每个叶子结点对应的哈夫曼编码*/ { char *cd, **hc; //容器 int i, start, p, last; hc = (char **)malloc((LeafNum) * sizeof(char *)); /*分配n个编码的头指针 */ if (1 == LeafNum) //只有一个叶子节点时 { hc[0] = (char *)malloc((LeafNum + 1) * sizeof(char)); strcpy(hc[0], "0"); return hc; } cd = (char *)malloc((LeafNum + 1) * sizeof(char)); /*分配求当前编码的工作空间 */ cd[LeafNum] = '