课设要求
(1)初始化 (Initialization):从终端读入n个字符,建立哈夫曼树;
(2)编码 (Coding):利用已建好的哈夫曼树,对字符进行编码,然后将正文编码结果存入文件codefile中;
(3)译码 (Decoding):利用已建好的哈夫曼树将文件codefile中的代码进行译码,结果存入文件textfile中。
上代码
#include<bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
typedef struct {
unsigned int weight;
unsigned int parent, lchild, rchild;
}HTNode, *HuffmanTree;
typedef char * * HuffmanCode;
//Select 2 smallest-weight nodes for merging
void Select(HuffmanTree &HT, int n, int& s1){
int maxx = inf;
for(int i = 0; i <= n; i++){
if(HT[i].weight<=maxx && HT[i].parent == 0){
maxx = HT[i].weight;
s1 = i;
}
}
HT[s1].parent = -1;
return;
}
//construct Huffman Tree
void HuffmanCoding(HuffmanTree &HT, HuffmanCode &HC, int *w, int n){
if(n<1) return;
int m = 2*n-1;
HT = (HuffmanTree)malloc((m+1)*sizeof(HTNode));
HuffmanTree p = HT; int i;
for(i = 0; i < n; i++