急球C++数据结构 哈夫曼编译程序代码

来源:百度知道 编辑:UC知道 时间:2024/07/08 01:39:37
具有以下功能:
(1)I:初始化(Initialization)。从指定的英文文件中Sourcefile.txt读取数据,根据文件内容统计的字符的频度,建立哈夫曼树。
(2)E:编码(Encoding)。利用已经建好的哈夫曼树进行编码,并将每个字符的编码写入文件HuffCode.txt中保存。
(3)C:压缩(Compress)。根据HuffCode.txt中编码对文件Sourcefile.txt进行重新编码,并将重新编码后的内容写入文件CodeFile.txt中。
(4)D:译码(Decoding)。利用已经建好的哈夫曼树将文件CodeFile.txt中的代码进行译码,结果存入文件TextFile中。
(5)P:打印代码文件(Print)。将文件CodeFile.txt的内容显示在终端上,每行50个代码。
测试数据
Sourcefile.txt中的内容如下:
I love data Structure, I love Computer。I will try my best to study data Structure.
(1)用户界面可以设计为“菜单”方式:显示上述功能符号,再加上“Q”选项,表示退出(Quit)。用户可以键入一个选择功能符。此功能执行完毕后再显示此菜单,直至某次用户选择了“Q”为止。
(2)根据Sourcefile.txt中每个字符出现的次数统计频度,对没有出现的字符一律不用编码。

# include<stdio.h>
#include<stdlib.h>
#define MAXLEN 100

typedef struct Huffmantree {
char ch; /*键值*/

int weight,mark; /*weight为权值,mark为标志域*/
struct Huffmantree *parent,*lchild,*rchild,*next;
}Hftree,*linktree;

/*整理输入的字符串,合并相同的项,并求出每个字符在数组中出现的次数 */
linktree tidycharacter(char character[])
{
int i=0;
linktree tree,ptr,beforeptr,node; /*链式 ,tree为头结点,beforeptr为ptr的前一结点,node为新申请的结点*/

tree=(linktree)malloc(sizeof(Hftree));/*创建单链表的头结点*/
if(!tree)return NULL;
tree->next=NULL; /* 头结点为空,且后续结点为空*/

for(i=0;character[i]!='\0'&&character[i]!='\n';i++) { /*遍历直到字符串结束为止*/
ptr=tree;
beforeptr=tree;

node=(linktree)malloc(sizeof(Hftree)); /*新申请结点node*/
if(!node)return NULL;
node->next=NULL;
node->parent=NULL;
node->lchild=NULL;
node->rchild=NULL; /*置空*/
node->mark=0