问题描述
利用哈弗曼编码进行通信可以大大提高信道利用率,缩短信息传输时间,降低传输成本。但是,这要求在发送端通过一个编码系统对待传数据预先编码,在接收端将传来的数据进行译码(复原)。对双工信道(即可以双向传输信息的信道),每端都需要一个完整的编/译码系统。试为这样的信息收发站写一个哈夫曼码的编/译码系统。
基本要求
(1)I:初始化(Initialization)。从终端读入字符集大小n,以及n个字符和n个权值,建立哈夫曼树。
(2)E:编码(Encoding)。利用以建好的哈夫曼树,对从终端输入的正文进行编码,然后把结果输出。
(3)D:译码(Decoding)。利用已建好的哈夫曼树将从终端输入的代码进行译码,然后把结果输出。
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct {
char ch;
int weight;
int parent;
int lchild, rchild;
}HTNode, * HuffmanTree;//哈夫曼树结点结构
typedef struct {
char* code;//哈夫曼编码
char ch; //字符
int start;
}HfmCode, * HfmCodeForm;//哈夫曼编码表编码结构
int MinVal(HuffmanTree& ht, int i) {
int k, min, cnt = 0;
while (ht[cnt].parent != -1) //找到没有双亲的结点
cnt++;
min = ht[cnt].weight;
k = cnt;
for (int j = cnt + 1; j < i; j++) {
if (ht[j].parent == -1 && ht[j].weight < min) {
min = ht[j].weight;
k = j;
}
}//找到权值最小的结点
ht[k].parent = 1; //双亲置为非空
return k;
}
void Select(HuffmanTree& ht, int i, int& s1, int& s2) {
int s;
s1 = MinVal(ht,i);
s2 = MinVal(ht,i);
if (s1 > s2) {
//三角置换,保持序号小在左,序号大在右
s = s1;
s1 = s2;
s2 = s;
}
}//为没有字符的结点寻找左孩子和右孩子
void InitHfmTree(HuffmanTree& ht, int n) {
ht = new HTNode[2 * n - 1];
for (int i

最低0.47元/天 解锁文章
1283

被折叠的 条评论
为什么被折叠?



