写在前面
现在时间是2021年11月25日下午2:24,在花费一晚上加两节自习加中午没睡觉,Joe树皮终于实现了她的HuffmanTree,中间N次调试发现错误的时候都让我很是怀疑,我是周树皮,不是周木头,错得我离谱,改得我吐血。 无语,快上课了,文章先开个头,后续会更新HuffmanTree的实现原理,顺便分享一下我的心酸调试过程。 发现我已经语无伦次了,管他管他我说的就是病句 555555想睡觉觉!!!!!!!!
1.术前准备
2.上机实操
2.1写个Bug
2.2De个Bug
3.附录
3.1完整代码
#include<stdio.h>
#include<malloc.h>
#define MAXSIZE 50
#define MaxValue 1000
typedef struct Node{
int weight;
int parent;
int lchild;
int rchild;
}HuffNode;
typedef struct Tarry{
HuffNode Tree[MAXSIZE];
int index;
}HuffTree;
void HuffmanTreeInit(HuffTree **HFTree,int TotalNode)
{
(*HFTree)=(HuffTree*)malloc((TotalNode+1)*sizeof(HuffNode));
(*HFTree)->index=-1;
}
void CreatHuffmanTree(HuffTree **HFTree,int NodeNum,int TotalNode)
{
HuffNode *PNode=(HuffNode*)malloc(sizeof(HuffNode));
printf("请依次输入%d个结点的权值:\n",NodeNum);
for((*HFTree)->index=1; (*HFTree)->index<=TotalNode;(*HFTree)->index++){
PNode=&(*HFTree)->Tree[(*HFTree)->index];
if((*HFTree)->index<=NodeNum){
scanf("%d",&PNode->weight);
}
else{
PNode->weight=0;
}
PNode->parent=0;
PNode->lchild=0;
PNode->rchild=0;
}
int min1,min2,x1,x2,flag=0;
int i;
for((*HFTree)->index=1; (*HFTree)->index<NodeNum;(*HFTree)->index++){
min1=min2=MaxValue;
x1=x2=0;
for(i=1;i<NodeNum+(*HFTree)->index;i++){
if((*HFTree)->Tree[i].parent==0&&(*HFTree)->Tree[i].weight<min1){
min2=min1;
x2=x1;
min1=(*HFTree)->Tree[i].weight;
x1=i;
}
else
if((*HFTree)->Tree[i].parent==0&&(*HFTree)->Tree[i].weight<min2){
min2=(*HFTree)->Tree[i].weight;
x2=i;
}
}
flag=(*HFTree)->index+NodeNum;
(*HFTree)->Tree[x1].parent=flag;
(*HFTree)->Tree[x2].parent=flag;
(*HFTree)->Tree[flag].weight=(*HFTree)->Tree[x1].weight+(*HFTree)->Tree[x2].weight;
(*HFTree)->Tree[flag].lchild=x1;
(*HFTree)->Tree[flag].rchild=x2;
}
printf("\n");
}
void PrintHuffmanTree(HuffTree *HFTree,int TotalNode)
{
HuffNode *PNode=(HuffNode*)malloc(sizeof(HuffNode));
printf("\t\tHuffman Graph\t\t\n");
printf("index\t weight\t parent\t lchild\t rchlid\t\n ");
printf("\n");
for(HFTree->index=1;HFTree->index<=TotalNode;HFTree->index++){
PNode=&(HFTree->Tree[HFTree->index]);
printf(" %d\t %d\t %d\t %d\t %d\t\n ",HFTree->index,PNode->weight,PNode->parent,PNode->lchild,PNode->rchild);
printf("\n");
}
}
int main()
{
HuffTree *HFTree;
int NodeNum;
int TotalNode;
printf("请输入创建结点个数:\n");
scanf("%d",&NodeNum);
TotalNode=2*NodeNum-1;
HuffmanTreeInit(&HFTree,TotalNode) ;
CreatHuffmanTree(&HFTree,NodeNum,TotalNode);
PrintHuffmanTree(HFTree,TotalNode);
return 0;
}
3.2测试结果
终于实现了!!!!
|