📄 hufftree.txt
字号:
#include <stdio.h>
#include <stdlib.h>
#include "error.h"
#include "hufftree.h"
#include <string.h>
//Hufftree.c//
/* function prototypes */
void TraceHuffTree(HuffTree, char *);
/* creates a new HuffTree */
HuffTree NewHuffTree(char c, int f)
{
HuffTree ht = malloc(sizeof(struct HuffNode));
if(ht == NULL)
{
FatalError("Not enough memory!");
}
/* set the character and frequency fields in the HuffNode */
ht->character = c;
ht->frequency = f;
left and right to NULL */
ht->left = NULL;
ht->right = NULL;
return ht;
}
/* Creates a new HuffTree with left and right pointing to the two
supplied HuffTrees */
HuffTree JoinHuffTrees(HuffTree q, HuffTree p)
{
HuffTree new = malloc(sizeof(struct HuffNode));
if(new == NULL)
{
FatalError("Not enough memory!");
}
/* since this tree doesn't carry any character information, just
set character to NULL */
new->character = '\0';
new->frequency = (q->frequency + p->frequency);
/* we want left to point to the smaller frequency */
if(q->frequency < p->frequency)
{
new->left = q;
new->right = p;
}
else if(q->frequency > p->frequency)
{
new->left = p;
new->right = q;
}
else
{
new->left = q;
new->right = p;
}
return new;
}
/* starts the output trace */
void OutputHuffCodes(HuffTree ht)
char initial_code[2] = '\0';
TraceHuffTree(ht,initial_code);
return;
}
/* traces the HuffTree, setting the huffcode to 0 for left and 1 for
right */
void TraceHuffTree(HuffTree ht,char *code)
{
char left_code[MAX_ARRAY], right_code[MAX_ARRAY],
special_char[MAX_ARRAY];
int sw;
sw = 0;
if(ht->character == '\0')
{
/* this must be one of the "joined" HuffTrees */
strcpy(left_code, code);
strcpy(right_code, code);
strcat(left_code, "0");
strcat(right_code, "1");
TraceHuffTree(ht->left, left_code);
}
else
{
/* this is not one of the "joined" HuffTrees, so output
its character, along with the trace code we've encountered
sofar to get here */
if(ht->character == '\n')
{
strcpy(special_char, "nl");
sw = 1;
}
else if(ht->character == ' ')
{
strcpy(special_char, "sp");
sw = 1;
}
else if(ht->character == '\a')
{
strcpy(special_char, "bell");
sw = 1;
}
}
else if(ht->character == ' ')
{
strcpy(special_char, "sp");
sw = 1;
}
else if(ht->character == '\a')
{
strcpy(special_char, "bell");
sw = 1;
}
if(sw)
{
printf("%-6s%s\n",special_char,code);
}
else
{
printf("%-6c%s\n",ht->character,code);
}
}
return;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -