Huffman编码实验

实验内容

构建哈夫曼树,并输出其对应的哈夫曼编码

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

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



void createHuffman(HuffmanTree HT,int n) {
    if (n<=1)
    {
        return;
    }
    int m = 2 * n - 1;
    HT = (HuffmanTree)malloc(sizeof(HTNode) * (m + 1));
    for (int i = 1; i < m; i++)
    {
        HT[i].parent = 0;
        HT[i].lchild = 0;
        HT[i].rchild = 0;
    }
    for (int j = 0; j <=n; j++)
    {
        scanf("%d", &HT[j].weight);
    }
    for (int i = n+1; i < m; i++)
    {
        select(HT, i - 1, s1, s2);
        HT[s1].parent = i;
        HT[s2].parent = i;
        HT[i].lchild = s1;
        HT[i].rchild = s2;
        HT[i].weight = HT[s1].weight + HT[s2].weight;
    }
}


void CreatHuffmanCode(HuffmanTree HT, int n) {
    char* HC = (char*)malloc(sizeof(char)*(n+1));
    char* cd = (char*)malloc(sizeof(char) * n);
    cd[n - 1] = '\0';
    for (int i = 0; i <=n; i++)
    {
        int start = n - 1;
        int c = i;
        int f = HT[i].parent;
        while (f!=0)
        {
            --start;
            if (HT[f].lchild == c)
                cd[start] = '0';
            else
            {
                cd[start] = '1';
            }
            c = f;
            f = HT[i].parent;
        }
        HC[i] = (char*)malloc(sizeof(n - start));
        strcpy(HC[i], &cd[start]);
    }
    free(cd);

}

 

好了,我们下回见,peace

posted @ 2020-09-26 09:42  野评测  阅读(222)  评论(0编辑  收藏  举报