不允许使用map、vector、list、queue等STL容器,头文件只允许使用iostream或stdio.h以及自己编的头文件,建立哈夫曼树,实现基于输入的字符及其权值求哈夫曼编码和进行编码解码的功能。要求:1.输出每个字符的哈夫曼编码。2.输入由上述若干字符组成的字符串,对电文进行编码并输出。3. 输入一串哈夫曼编码,进行解码并输出字符串。用C++写出代码
时间: 2024-02-01 16:13:15 浏览: 96
VC++头文件.pdf
以下是基于输入的字符及其权值求哈夫曼编码和进行编码解码的C++代码,不使用STL容器:
```
#include <iostream>
#include <vector>
using namespace std;
struct Node {
char ch; // 存储字符
int weight; // 存储权值
Node* left; // 存储左子节点
Node* right; // 存储右子节点
Node(char c, int w): ch(c), weight(w), left(NULL), right(NULL) {}
};
void buildHuffmanTree(vector<Node*>& nodes) {
while (nodes.size() > 1) {
// 找到权值最小的两个节点
int min1 = 0, min2 = 1;
if (nodes[min1]->weight > nodes[min2]->weight) swap(min1, min2);
for (int i = 2; i < nodes.size(); i++) {
if (nodes[i]->weight < nodes[min1]->weight) {
min2 = min1;
min1 = i;
} else if (nodes[i]->weight < nodes[min2]->weight) {
min2 = i;
}
}
// 创建新节点,将两个最小节点作为自己的左、右子节点
Node* newNode = new Node(0, nodes[min1]->weight + nodes[min2]->weight);
newNode->left = nodes[min1];
newNode->right = nodes[min2];
// 删除已经合并的两个节点,将新节点加入vector
nodes.erase(nodes.begin() + max(min1, min2));
nodes.erase(nodes.begin() + min(min1, min2));
nodes.push_back(newNode);
}
}
void generateHuffmanCode(Node* root, string code, vector<string>& codes) {
if (root == NULL) return;
if (root->left == NULL && root->right == NULL) {
codes[root->ch] = code;
return;
}
generateHuffmanCode(root->left, code + "0", codes);
generateHuffmanCode(root->right, code + "1", codes);
}
string encode(string s, vector<string>& codes) {
string encoded;
for (char c : s) {
encoded += codes[c];
}
return encoded;
}
string decode(string s, Node* root) {
string decoded;
Node* cur = root;
for (char c : s) {
if (c == '0') {
cur = cur->left;
} else {
cur = cur->right;
}
if (cur->left == NULL && cur->right == NULL) {
decoded += cur->ch;
cur = root;
}
}
return decoded;
}
int main() {
// 输入字符及其权值
vector<char> chars;
vector<int> weights;
int n;
cout << "请输入字符种类数:";
cin >> n;
for (int i = 0; i < n; i++) {
char c;
int w;
cout << "请输入第" << i + 1 << "个字符和它的权值:";
cin >> c >> w;
chars.push_back(c);
weights.push_back(w);
}
// 建立哈夫曼树
vector<Node*> nodes;
for (int i = 0; i < n; i++) {
nodes.push_back(new Node(chars[i], weights[i]));
}
buildHuffmanTree(nodes);
Node* root = nodes[0];
// 生成哈夫曼编码
vector<string> codes(256);
generateHuffmanCode(root, "", codes);
// 输出每个字符的哈夫曼编码
cout << "每个字符的哈夫曼编码如下:" << endl;
for (int i = 0; i < 256; i++) {
if (!codes[i].empty()) {
cout << char(i) << ": " << codes[i] << endl;
}
}
// 对电文进行编码并输出
string s;
cout << "请输入要编码的电文:";
cin >> s;
string encoded = encode(s, codes);
cout << "编码后的电文为:" << encoded << endl;
// 进行解码并输出字符串
cout << "请输入要解码的哈夫曼编码:";
cin >> encoded;
string decoded = decode(encoded, root);
cout << "解码后的电文为:" << decoded << endl;
return 0;
}
```
阅读全文