资源简介
1、对输入的字符串统计出现频率,进行哈夫曼编码。。
2、生成的哈夫曼编码以及哈夫曼树可保存到本地文件。。
3、对接下来输入的01字符串,用先前的哈夫曼编码进行解码。。
4、全过程C语言实现。。
代码片段和文件信息
#include
#include
#include
#include
#define MAX_CHAR_KINDS 128//字符种类最大值。。
#define MAX_NUM 1000//字符串最大长度。。
FILE *in *ou;
typedef struct TreeNode
{
int weight;
int id;
short isLeaf;
char data;
char bin;//0或者1。。
struct TreeNode *parent;
struct TreeNode *lChild *rChild;
} TreeNode;
typedef struct
{
char data;
char code[MAX_CHAR_KINDS];
} Code;
//字符串倒置。。
void ReverseStr(char *str)
{
int i;
char c;
int length;
length = strlen(str);
for (i = 0; i < length / 2; i++)
{
c = str[length - 1 - i];
str[length - 1 - i] = str[i];
str[i] = c;
}
}
void PreOrderTraverse(TreeNode *t)
{
if ((t->rChild == NULL) && (t->lChild == NULL))
{
t->isLeaf = 1;
}
else
{
t->isLeaf = 0;
}
if (t->parent != NULL)
{
t->id = 2 * t->parent->id + (int)t->bin - 48;
}
else
{
t->id = 1;
t->bin = ‘ ‘;
}
if (t->isLeaf == 1)
{
fprintf(ou “%6d%5c%8d ‘%c‘\n“ t->id t->bin t->isLeaf t->data);
}
else
{
fprintf(ou “%6d%5c%8d\n“ t->id t->bin t->isLeaf);
}
if (t->lChild != NULL)
{
PreOrderTraverse(t->lChild);
}
if (t->rChild != NULL)
{
PreOrderTraverse(t->rChild);
}
}
int main()
{
char str[MAX_NUM];
char pwd[MAX_NUM];
TreeNode *HFTree;
int i j;
int length;//字符串长度。。
int count;//不同字符个数。。
TreeNode *tree[MAX_CHAR_KINDS];//初始的几个小树。。
TreeNode *eachChar[MAX_CHAR_KINDS];
TreeNode *temp *p;
Code *HFCode;
int codeBit;
short existed;
//输入,初始化。。
printf(“Input string to encode:\n“);
gets(str);
printf(“\n“);
length = strlen(str);
count = 0;
//开始统计字符串中各个字符出现的次数。。
for (i = 0; i < length; i++)
{
existed = 0;
for (j = 0; j < count; j++)
{
if (str[i] == tree[j]->data)
{
tree[j]->weight++;
existed = 1;
break;
}
}
//如果不是现有的字符,拿个新盒子装。。
if (existed == 0)
{
tree[count] = (TreeNode *)malloc(sizeof(TreeNode));
tree[count]->weight = 1;
tree[count]->data = str[i];
tree[count]->parent = NULL;
tree[count]->lChild = NULL;
tree[count]->rChild = NULL;
eachChar[count] = tree[count];//备份。。
count++;
}
}
//非法输入。。
if (count == 0)
{
printf(“No char!\n“);
getch();
return (0);
}
else if (count == 1)
{
printf(“At least 2 kinds of char!\n“);
getch();
return (0);
}
//冒泡,升序。。
for (i = 0; i < count - 1; i++)
{
for (j = 0; j < count - 1 - i; j++)
{
if (tree[j]->weight > tree[j+1]->weight)
{
temp = tree[j];
tree[j] = tree[j+1];
tree[j+1] = temp;
}
}
}
//生成Huffman树。。
for (i = 1; i < count; i++)
{
temp = (TreeNode *)malloc(sizeof(TreeNode));
temp->lChild = tree[i-1];
相关资源
- C++中头文件与源文件的作用详解
- C语言代码高亮html输出工具
- 猜数字游戏 c语言代码
- C语言课程设计
- 数字电位器C语言程序
- CCS FFT c语言算法
- 使用C语言编写的病房管理系统
- 通信过程中的RS编译码程序(c语言)
- 计算机二级C语言上机填空,改错,编
- 用回溯法解决八皇后问题C语言实现
- 简易教务管理系统c语言开发文档
- 操作系统课设 读写者问题 c语言实现
- 小波变换算法 c语言版
- C流程图生成器,用C语言代码 生成C语
- 3des加密算法C语言实现
- 简单的C语言点对点聊天程序
- 单片机c语言源程序(51定时器 八个按
- 个人日常财务管理系统(C语言)
- c语言电子商务系统
- 小甲鱼C语言课件 源代码
- 将图片转换为C语言数组的程序
- C语言实现的一个内存泄漏检测程序
- DES加密算法C语言实现
- LINUX下命令行界面的C语言细胞游戏
- 用单片机控制蜂鸣器播放旋律程序(
- 学校超市选址问题(数据结构C语言版
- 电子时钟 有C语言程序,PROTEUS仿真图
- 尚观培训linux许巍老师关于c语言的课
- 算符优先语法分析器(C语言编写)
- 基于C语言的密码锁程序
评论
共有 条评论