用c语言实现哈夫曼编码 输入一行字符串,由长度不超过255个字符的小写英文字母组成要求输出有若干行,每行由两部分组成,一个字母和该字母出现的频率,频率按高到低排序,频率相同则按asc码的先后顺序排列
时间: 2024-02-22 21:59:04 浏览: 80
好的,下面是一个C语言的实现示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 26
struct HuffmanNode {
char ch;
int freq;
struct HuffmanNode *left, *right;
};
struct HeapNode {
struct HuffmanNode *data;
struct HeapNode *next;
};
struct Heap {
struct HeapNode *head, *tail;
};
struct HuffmanNode* createHuffmanNode(char ch, int freq) {
struct HuffmanNode *node = (struct HuffmanNode*)malloc(sizeof(struct HuffmanNode));
node->ch = ch;
node->freq = freq;
node->left = node->right = NULL;
return node;
}
struct HeapNode* createHeapNode(struct HuffmanNode *data) {
struct HeapNode *node = (struct HeapNode*)malloc(sizeof(struct HeapNode));
node->data = data;
node->next = NULL;
return node;
}
struct Heap* createHeap() {
struct Heap *heap = (struct Heap*)malloc(sizeof(struct Heap));
heap->head = heap->tail = NULL;
return heap;
}
void push(struct Heap *heap, struct HuffmanNode *data) {
struct HeapNode *node = createHeapNode(data);
if (heap->head == NULL) {
heap->head = heap->tail = node;
} else {
heap->tail->next = node;
heap->tail = node;
}
}
struct HuffmanNode* pop(struct Heap *heap) {
struct HeapNode *node = heap->head;
heap->head = heap->head->next;
if (heap->head == NULL) {
heap->tail = NULL;
}
struct HuffmanNode *data = node->data;
free(node);
return data;
}
void buildHuffmanTree(struct Heap *heap) {
while (heap->head != heap->tail) {
struct HuffmanNode *left = pop(heap);
struct HuffmanNode *right = pop(heap);
struct HuffmanNode *parent = createHuffmanNode('\0', left->freq + right->freq);
parent->left = left;
parent->right = right;
push(heap, parent);
}
}
void printHuffmanCode(struct HuffmanNode *root, char *buf, int depth) {
if (!root->left && !root->right) {
buf[depth] = '\0';
printf("%c %s\n", root->ch, buf);
return;
}
if (root->left) {
buf[depth] = '0';
printHuffmanCode(root->left, buf, depth + 1);
}
if (root->right) {
buf[depth] = '1';
printHuffmanCode(root->right, buf, depth + 1);
}
}
int cmp(const void *a, const void *b) {
struct HuffmanNode **pa = (struct HuffmanNode**)a;
struct HuffmanNode **pb = (struct HuffmanNode**)b;
if ((*pa)->freq != (*pb)->freq) {
return (*pb)->freq - (*pa)->freq;
}
return (*pa)->ch - (*pb)->ch;
}
int main() {
char str[256];
int cnt[MAXN] = {0};
fgets(str, 256, stdin);
int len = strlen(str) - 1;
for (int i = 0; i < len; i++) {
cnt[str[i] - 'a']++;
}
qsort(cnt, MAXN, sizeof(int), cmp);
struct Heap *heap = createHeap();
for (int i = 0; i < MAXN; i++) {
if (cnt[i] == 0) {
break;
}
struct HuffmanNode *node = createHuffmanNode('a' + i, cnt[i]);
push(heap, node);
}
buildHuffmanTree(heap);
char buf[256];
printHuffmanCode(heap->head->data, buf, 0);
return 0;
}
```
上述代码中,我们使用了链表实现了一个最小堆,然后使用堆来构建哈夫曼树。最后,我们使用递归的方式输出每个叶子节点对应的哈夫曼编码。请注意,本题中要求按照频率的高低和字母的先后顺序排序,因此我们在排序函数中进行了处理。
阅读全文