数据结构课设----哈夫曼树及其编码实现

#include 
#include 
#include 
#include 

typedef struct {
    unsigned int weight;
    unsigned int parent, lchild, rchild;
} HTNode, * HuffmanTree;

typedef char** HuffmanCode;

unsigned int min1, min2;

void Select(HuffmanTree HT, int e, int* s1, int* s2) {
    min1 = min2 = INT_MAX;
    *s1 = *s2 = 0;

    for (int i = 1; i <= e; ++i) {
        if (HT[i].weight < min1 && !HT[i].parent) {
            min2 = min1;
            *s2 = *s1;
            min1 = HT[i].weight;
            *s1 = i;
        }
        else if (HT[i].weight < min2 && !HT[i].parent) {
            min2 = HT[i].weight;
            *s2 = i;
        }
    }
    //    printf("%d %d\n", *s1, *s2);
}

void HuffmanCoding(HuffmanTree* HT, HuffmanCode* HC, int* w, int n) {
    if (n <= 1) return;
    int m = 2 * n - 1;  //由叶子结点计算总结点数
    *HT = (HuffmanTree)malloc((m + 1) * sizeof(HTNode));

    int i;
    HuffmanTree p;
    for (p = *HT + 1, i = 1; i <= n; ++i, ++p, ++w)
        p->weight = *w, p->parent = 0, p->lchild = 0, p->rchild = 0;    //不使用0号位
    for (; i <= m; ++i, ++p) p->weight = 0, p->parent = 0, p->lchild = 0, p->rchild = 0;

    p = *HT;
    for (i = n + 1; i <= m; ++i) {
        int s1, s2;
        Select(*HT, i - 1, &s1, &s2);
        p[s1].parent = i;
        p[s2].parent = i;
        p[i].lchild = s1;
        p[i].rchild = s2;
        p[i].weight = p[s1].weight + p[s2].weight;
    }

    //    for (i = 1; i <= m; i++)
    //        printf("%d: %d,%d,%d,%d\n", i, p[i].weight, p[i].parent, p[i].lchild, p[i].rchild);

    *HC = (HuffmanCode)malloc(n + 1 * sizeof(char*)); //分配n个字符编码的头指针向量
    char* cd = (char*)malloc(n * sizeof(char));
    cd[n - 1] = '\0';

    for (i = 1; i <= n; ++i) {
        int start = n - 1;
        for (int c = i, f = (int)p[i].parent; f != 0; c = f, f = (int)p[f].parent)    //从叶子结点到根逆向求编码
            if (p[f].lchild == c) cd[--start] = '0';
            else cd[--start] = '1';

        (*HC)[i] = (char*)malloc((n - start) * sizeof(char));
        strcpy((*HC)[i], &cd[start]);
    }
    //    printf("%s\n", *cd);
    free(cd);
}

int main() {
    HuffmanTree t;
    HuffmanCode c;
    int n, weight[100];

    printf("请输入结点个数:");
    scanf_s("%d", &n);
    for (int i = 0; i < n; ++i) {
        printf("第%d个结点权值:", i + 1);
        scanf_s("%d", &weight[i]);
    }

    HuffmanCoding(&t, &c, weight, n);

    printf("编码如下:\n");
    for (int i = 1; i <= n; ++i)
        printf("%d: %s\n", t[i].weight, c[i]);
    return 0;
}

你可能感兴趣的:(其他,c语言,c++)