自己实现了一个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,"");
}