先上代码:(问题在红色字体部分):原码在53课时赫夫曼编码C语言实现 由于代码太多我从上面选了一部分复制下来:
htTree * buildTree(char *inputString)
{
int * probability = (int *)malloc(sizeof(int)*256);
for(int i=0; i<256; i++)
probability[i]=0;
for(i=0; inputString[i]!='\0'; i++)
probability[(unsigned char) inputString[i]]++;
pQueue * huffmanQueue;
initPQueue(&huffmanQueue);
for(i=0; i<256; i++)
if(probability[i]!=0)
{
htNode *aux = (htNode *)malloc(sizeof(htNode));
aux->left = NULL;
aux->right = NULL;
aux->symbol = (char) i;
addPQueue(&huffmanQueue,aux,probability[i]);
}
free(probability) ; //我调试了程序之后发现这里为什么是每次循环都要释放一次,而不是一次就释放完成!为什么!
while(huffmanQueue->size!=1)
{
int priority = huffmanQueue->first->priority;
priority+=huffmanQueue->first->next->priority;
htNode *left = getPQueue(&huffmanQueue);
htNode *right = getPQueue(&huffmanQueue);
htNode *newNode = (htNode *)malloc(sizeof(htNode));
newNode->left = left;
newNode->right = right;
addPQueue(&huffmanQueue,newNode,priority);
}
htTree *tree = (htTree *) malloc(sizeof(htTree));
tree->root = getPQueue(&huffmanQueue);
return tree;
}
void encode(hlTable *table, char *stringToEncode)
{
hlNode *traversal;
printf("\nEncoding\nInput string : %s\nEncoded string : \n",stringToEncode);
for(int i=0; stringToEncode[i]!='\0'; i++)
{
traversal = table->first;
while(traversal->symbol != stringToEncode[i])
traversal = traversal->next;
printf("%s",traversal->code);
}
printf("\n");
}
|