关于哈弗曼编码的一个问题
程序代码:
#include "iostream.h" #include "malloc.h" #include "string.h" #define MAXSIZE 30 #define MAX 100 typedef struct { char data; int weight; int parent; int left; int right; }HTNode, *HuffmanTree; typedef char **HuffmanCode; typedef struct { char data; int weight; }Tdata; HuffmanTree HT; HuffmanCode HC; void SelectMinTree(HuffmanTree HT,int n,int *s1,int *s2); void HuffmanCoding(HuffmanTree HT,Tdata *w,int n); void SelectMinTree(HuffmanTree HT,int n,int *s1,int *s2) { int i,min1,min2; *s2=*s1=0; min1=min2=MAX; for(i=1;i<=n;i++) { if (HT[i].parent==0) if (HT[i].weight<min1) { min2=min1; min1=HT[i].weight; *s2=*s1; *s1=i; } else if (HT[i].weight<min2) { min2=HT[i].weight; *s2=i; } } } void HuffmanCoding(HuffmanTree HT,Tdata *w,int n) { int m,i,s1,s2,start,c,f; HTNode *p; char *cd; if(n<=1)return; m=2*n-1; HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode)); for(p=HT+1,i=1;i<=n;i++,p++) { p->data=w[i].data; p->weight=w[i].weight; p->left=0; p->right=0; p->parent=0; } for(;i<=m;i++,p++) { p->weight=0; p->left=0; p->right=0; p->parent=0; } for(i=n+1;i<=m;i++) { SelectMinTree(HT,i-1,&s1,&s2); HT[s1].parent=i;HT[s2].parent=i; HT[i].left=s1;HT[i].right=s2; HT[i].weight=HT[s1].weight+HT[s2].weight; } HC=(HuffmanCode)malloc((n+1)*sizeof(char *)); cd=(char *)malloc(n*sizeof(char)); cd[n-1]='\0'; for(i=1;i<=n;i++) { start=n-1; for(c=i,f=HT[i].parent;f!=0;c=f,f=HT[f].parent) if (HT[f].left==c) cd[--start]='0'; else cd[--start]='1'; HC[i]=(char *)malloc((n-start)*sizeof(char)); strcpy(HC[i],&cd[start]); } free(cd); } void main() { Tdata w[MAXSIZE]; int n,i; cout<<"请输入元素数:"; cin>>n; for(i=1;i<=n;i++) { cout<<"input"<<i<<"data name and weight:"; cin>>w[i].data>>w[i].weight; } cout<<"*************result*************"<<endl; HuffmanCoding(HT,w,n); for(i=1;i<=n;i++) cout<<w[i].data<<"----------->"<<HC[i]<<endl; }
其中SelectMinTree函数在HuffmanCoding函数中传入的实参为什么是i-1呢?
&s1,&s2是指针吗?
为什么要在这里变成指针传值啊?
还有为什么HT在动态申请的时候要申请m+1个啊?HC为什么申请了n+1个?
后面为什么是p=HT+1而不是p=HT呢?
cd[n-1]='\0'是什么意思?
问题有点多,嘿嘿,谢谢好心人啦~