huffman编码

自己实现了一个huffman树

好久不用C了很多函数早就忘了呵呵 

huffman的树对应于算法导论的P232

#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct HuffNode
{
    int weight;
    struct HuffNode *parent;
    struct HuffNode *lchild;
    struct HuffNode *rchild;
}HuffNode,*ptrHuffman;

ptrHuffman extract_min(HuffNode **array,int n)
{
    ptrHuffman pre=array[0];
    int i=1;
    for(i=1;i<n;i++)
    {
        if(pre->weight>array[i]->weight)
        {
            array[i-1]=pre;
            pre=array[i];
        }
        else
        {
            array[i-1]=array[i];
        }
    }
   // printf("%d",pre.weight);
    return pre;
}

int insert(HuffNode **array,int n,ptrHuffman huff)
{
    array[n-1]=huff;
    return n++;
}
ptrHuffman makeHuffman(int *a,int n)
{
    ptrHuffman *head=(ptrHuffman*)malloc(sizeof(ptrHuffman)*n);
    int i;
    for(i=0;i<n;i++)
    {
        ptrHuffman pre=(ptrHuffman)malloc(sizeof(HuffNode));
        pre->weight=a[i];
        pre->lchild=pre->parent=pre->rchild=NULL;
        insert(head,i+1,pre);
         //printf("%d",pre->weight);
    }
    ptrHuffman pre1;
    //printf("rc ");
    for(i=n-1;i>=1;i--)
    {
        pre1=(ptrHuffman)malloc(sizeof(HuffNode));

        ptrHuffman lc=extract_min(head,i+1);
       // printf("lc %d",lc->weight);
        ptrHuffman rc=extract_min(head,i);
        // printf("rc %d\n",rc->weight);
       // printf("rc %d ",rc->weight);
        lc->parent=rc->parent=pre1;
        pre1->lchild=lc;
        pre1->rchild=rc;
     //   printf("lc %d ",lc->weight);

        pre1->weight=lc->weight+rc->weight;

        //printf("pre %d\n",pre1->weight);
        insert(head,i,pre1);
    }
    return pre1;
}
void print(ptrHuffman head,char *a)
{
    char tmp[15];
    strcpy(tmp,a);
    if(head->lchild!=NULL)
    {
        tmp[strlen(a)]='0';
        tmp[strlen(a)+1]='\0';
         print(head->lchild,tmp);

    }
    if(head->rchild!=NULL)
    {
         tmp[strlen(a)]='1';
         tmp[strlen(a)+1]='\0';
        print(head->rchild,tmp);
    }
    if(NULL==head->lchild)
    {
        printf("%d,%s\n",head->weight,a);
    }
}
int main()
{
    int a[6]={45,12,13,5,9,16};
    ptrHuffman head=makeHuffman(a,6);
   // printf("%d",head->weight);
   print(head,"");

}


转载于:https://my.oschina.net/u/2322146/blog/406226

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值