数据结构C语言-哈夫曼树以及哈夫曼编码

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

#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int status;
typedef int ElemType;

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

void Select(HuffmanTree HT,int num,int *s1,int *s2)
{
    int i=1,min=1000;
    for(;i<=num;i++)
    {
        if(HT[i].parent==0&&HT[i].weight<min)
        {
            min=HT[i].weight;
            *s1=i;
        }
    }
    HT[*s1].parent=1;
    min=1000;
    for(i=1;i<=num;i++)
    {
        if(HT[i].parent==0&&HT[i].weight<min)
        {
            min=HT[i].weight;
            *s2=i;
        }
    }
    HT[*s2].parent=1;
}

void CreateHuffmanTree(HuffmanTree HT,int n)
{
    if(n<=1)
        return;
    int m=2*n-1,i;
    //*HT=(HTNode *)malloc(sizeof(HTNode)*(m+1));
    for(i=1;i<=m;i++)
    {
        HT[i].parent=0;
        HT[i].lchild=0;
        HT[i].rchild=0;
    }
    int w[8]={5,29,7,8,14,23,3,11};//8
    for(i=1;i<=n;i++)
        HT[i].weight=w[i-1];

    int s1,s2;
    for(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;
    }
}

typedef char **HuffmanCode;

//只要在子函数中改变的数需要保留就用指针
void  CreateHuffmanCode(HuffmanTree HT,HuffmanCode *HC,int n)
{
    //*HC存着n个编码串的地址
    *HC=(char **)malloc(sizeof(char *)*(n+1));
    char *cd=(char *)malloc(sizeof(char)*n);
    cd[n-1]='\0';//指针可以当成数组用,编码最长n-1
    int i=1;
    for(;i<=n;i++)
    {
        int start=n-1,c=i,f=HT[i].parent;
        while(f!=0)
        {
            --start;
            if(HT[f].lchild==c)
                cd[start]='0';
            else
                cd[start]='1';
            c=f;
            f=HT[f].parent;
        }
        (*HC)[i]=(char *)malloc(sizeof(char)*(n-start));
        strcpy((*HC)[i],&cd[start]);//strcpy(char *,char *)
    }
    free(cd);
}

void PrintCode(HuffmanTree HT,HuffmanCode HC,int n)
{
    int i=1;
    for(;i<=n;i++)
    {
        printf("%d的编码是%s\n",HT[i].weight,HC[i]);
    }
}

int main()
{
    int n=8;
    HTNode HT[2*n];
    CreateHuffmanTree(HT,n);
    int i=1;
    for(;i<2*n;i++)
        printf("%d ",HT[i].weight);
    printf("\n");
    HuffmanCode HC;
    CreateHuffmanCode(HT,&HC,n);
    PrintCode(HT,HC,n);
    return 0;
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值