哈夫曼编码

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

《数据结构》实验报告4

年级2012级学号201202024061 姓名王冠文成绩

专业计算机科学与技术实验地点电教楼303 指导教师杨丽

实验日期月日

实验项目哈夫曼编码

一、实验目的

根据最优二叉树构造哈夫曼编码利用哈夫曼树很容易求出给定字符集及其概率分布的最优前缀码。哈夫曼编码正是一种应用非常广泛,本次试验通过设计一个算法,体会和掌握哈夫曼编码要点。

二、实验问题描述

已知每一个字符出现的频率,构造哈夫曼树,并设计哈夫曼编码。

三、实验步骤

1、实验问题分

给定字符集的哈夫曼树生成后,求哈夫曼编码的具体实现过程是:依次以叶子T[i]为出发点,向上回溯至根为止。上溯时走左分支则生成代码0,走右分支则生成代码。

2、构思算法

3、功能函数设计

4、编写程序并运行调试

四、实验结果(程序)及分析

#include

#include

#include

#include

#define MAX_CHAR_KINDS 128

#define MAX_NUM 1000

typedef struct TreeNode

{

int weight;

char data;

char bin;

struct TreeNode *parent;

struct TreeNode *lChild, *rChild;

} TreeNode;

typedef struct

{

char data;

char code[MAX_CHAR_KINDS];

} Code;

void InverseStr(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;

}

}

int main()

{

char str[MAX_NUM];

TreeNode *HFTree;

int i, j;

int length;

int count;

TreeNode *tree[MAX_CHAR_KINDS];//初始的几个小树。。TreeNode *eachChar[MAX_CHAR_KINDS];

TreeNode *temp;

Code *HFCode;

int codeBit;

short existed;

printf("王冠文201202024061");

printf("\n");

printf("Input string:");

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);

}

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;

}

}

}

for (i = 1; i < count; i++)

{

temp = (TreeNode *)malloc(sizeof(TreeNode));

temp->lChild = tree[i-1];

temp->rChild = tree[i];

temp->parent = NULL;

temp->weight = tree[i-1]->weight + tree[i]->weight;

tree[i-1]->parent = temp;

tree[i-1]->bin = '0';

tree[i]->parent = temp;

tree[i]->bin = '1';

tree[i] = temp;

for (j = i; j < count - 1; j++)

{

if (tree[j]->weight > tree[j+1]->weight)

{

temp = tree[j];

tree[j] = tree[j+1];

tree[j+1] = temp;

相关文档
最新文档