哈弗曼编码
											 程序代码:
程序代码:#include "stdio.h"
#define MAXVALUE 10000
typedef struct  
{
    int weight;
    int lchild;
    int rchild;
    int flag;
    int parent;
}HuffNode;
typedef struct  
{
    int weight;
    int len;
    char code[100];
}Code;
void Create(int weight[],HuffNode huff[],int n)
{
    for(int i=0;i<2*n-1;i++)                   //n个叶子结点有2n-1个结点
    {
        huff[i].weight=(i<n)?weight[i]:0;
        huff[i].lchild=-1;
        huff[i].rchild=-1;
        huff[i].flag=0;
        huff[i].parent=-1;
    }
}
void Huffman(HuffNode huff[],int n)
{
    int m1,m2;
    int x1,x2;
    for(int i=0;i<n;i++)
    {
        m1=m2=MAXVALUE; 
        x1=-1;
        x2=-1;
    
        for(int j=0;j<n+i;j++)
        {
            if(huff[j].flag==0)
            {
                if(huff[j].weight<m2)
                {
                    m1=m2;
                    x1=x2;
                    
                    m2=huff[j].weight;
                    x2=j;
                }
                else if(huff[j].weight<m1)
                {
                    m1=huff[j].weight;
                    x1=j;
                }
            }
        }
        huff[n+i].weight=huff[x1].weight+huff[x2].weight;
        huff[n+i].lchild=x1;
        huff[n+i].rchild=x2;
        huff[x1].parent=n+i;
        huff[x2].parent=n+i;
        huff[x1].flag=1;
        huff[x2].flag=1;
    }
}
void HuffCode(HuffNode huff[],int n,Code code[])
{
    int parent;
    int child;
    Code cd;
    int t;
    
    
    
    for(int i=0;i<n;i++)
    {
        code[i].weight=huff[i].weight;
        code[i].len=0;    
        
        child=i;
        cd.len=0;
        parent=huff[child].parent;
        t=0;
        while (parent!=-1)
        {
            cd.code[cd.len++]=(huff[parent].lchild==child)?'1':'0';
            child=parent;
            
            parent=huff[child].parent;
        }
        for(int j=0;j<cd.len;j--)
        {
            code[i].code[j]=cd.code[t];
            t++;
            
        }
        code[i].len=cd.len;
    }
}
void Print(Code code[],int n)
{
    printf("Output Code:");
    for(int i=0;i<n;i++)    
        printf("%s",code[i].code);
}
void main()
{
    int weight[5]={27,3,76,99,12};
    HuffNode huff[100];
    Code code[100];
    Create(weight,huff,5);
    Huffman(huff,5);
    HuffCode(huff,5,code);
}										
					
	


 
											





 
	    

 
	

