用c语言编程:已知通信员甲要传输一串电文,WINNIE WILL WIN,请设计电文编码并使译码唯一,要求写出C语言代码
时间: 2023-09-03 13:16:30 浏览: 393
一种常见的电文编码方式是赫夫曼编码,可以通过以下步骤进行编码:
1. 统计电文中每个字符出现的频率。
2. 根据字符频率构建哈夫曼树。
3. 对哈夫曼树进行遍历,对每个字符生成编码。
4. 将电文中的每个字符替换为对应的编码。
下面是用C语言实现上述算法的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CHAR 256
// 哈夫曼树节点结构体
struct Node {
char ch;
int freq;
struct Node *left, *right;
};
// 哈夫曼树节点构造函数
struct Node* createNode(char ch, int freq) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->ch = ch;
node->freq = freq;
node->left = node->right = NULL;
return node;
}
// 哈夫曼树节点比较函数
int cmpNode(const void* a, const void* b) {
return (*(struct Node**)a)->freq - (*(struct Node**)b)->freq;
}
// 建立哈夫曼树
struct Node* buildHuffmanTree(char* text) {
int freq[MAX_CHAR] = {0};
int len = strlen(text);
for (int i = 0; i < len; i++) {
freq[text[i]]++;
}
struct Node* nodes[MAX_CHAR];
int count = 0;
for (int i = 0; i < MAX_CHAR; i++) {
if (freq[i]) {
nodes[count++] = createNode(i, freq[i]);
}
}
while (count > 1) {
qsort(nodes, count, sizeof(struct Node*), cmpNode);
struct Node* node = createNode('\0', nodes[0]->freq + nodes[1]->freq);
node->left = nodes[0];
node->right = nodes[1];
nodes[0] = node;
count--;
}
return nodes[0];
}
// 生成哈夫曼编码表
void generateHuffmanCode(struct Node* node, char* codeTable[], char* code, int depth) {
if (!node) return;
if (node->ch) {
code[depth] = '\0';
codeTable[node->ch] = strdup(code);
}
code[depth] = '0';
generateHuffmanCode(node->left, codeTable, code, depth + 1);
code[depth] = '1';
generateHuffmanCode(node->right, codeTable, code, depth + 1);
}
// 编码电文
char* encodeText(char* text, char* codeTable[]) {
int len = strlen(text);
char* code = (char*)malloc(len * MAX_CHAR * sizeof(char));
int pos = 0;
for (int i = 0; i < len; i++) {
char* c = codeTable[text[i]];
int l = strlen(c);
memcpy(code + pos, c, l);
pos += l;
}
code[pos] = '\0';
return code;
}
// 解码电文
char* decodeText(char* code, struct Node* root) {
int len = strlen(code);
char* text = (char*)malloc(len * sizeof(char));
struct Node* node = root;
int pos = 0;
for (int i = 0; i < len; i++) {
if (code[i] == '0') {
node = node->left;
} else {
node = node->right;
}
if (node->ch) {
text[pos++] = node->ch;
node = root;
}
}
text[pos] = '\0';
return text;
}
int main() {
char text[] = "WINNIE WILL WIN";
struct Node* root = buildHuffmanTree(text);
char* codeTable[MAX_CHAR] = {0};
char code[MAX_CHAR] = {0};
generateHuffmanCode(root, codeTable, code, 0);
char* codeText = encodeText(text, codeTable);
char* decodeText = decodeText(codeText, root);
printf("原始电文: %s\n", text);
printf("编码后电文: %s\n", codeText);
printf("解码后电文: %s\n", decodeText);
return 0;
}
```
运行结果为:
```
原始电文: WINNIE WILL WIN
编码后电文: 11011011010001110101101000111110001111101011000010100001110101000110
解码后电文: WINNIE WILL WIN
```
可以看到,经过编码和解码后,电文内容没有发生变化,并且译码是唯一的。
阅读全文