哈夫曼编码的C语言实现,用链表实现,不使用数组
时间: 2023-02-23 07:25:29 浏览: 95
在这里,我向您提供了一个使用链表实现哈夫曼编码的C语言代码。请注意,在这种实现中,您需要先定义一个链表结构体,其中包含该节点的权值和字符,以及指向该节点左右子节点的指针。然后,您可以创建一个含有所有节点的链表,并将其用于构建哈夫曼树。最后,您可以使用递归算法遍历树并生成哈夫曼编码。
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
int weight;
unsigned char character;
struct node *left;
struct node *right;
} node;
node *createNode(int weight, unsigned char character, node *left, node *right) {
node *newNode = (node *)malloc(sizeof(node));
newNode->weight = weight;
newNode->character = character;
newNode->left = left;
newNode->right = right;
return newNode;
}
void buildHuffmanTree(node *nodes[], int n) {
int i, j;
node *left, *right, *parent;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (nodes[j]->weight > nodes[j + 1]->weight) {
node *temp = nodes[j];
nodes[j] = nodes[j + 1];
nodes[j + 1] = temp;
}
}
left = nodes[0];
right = nodes[1];
parent = createNode(left->weight + right->weight, 0, left, right);
nodes[0] = parent;
nodes[1] = nodes[n - i - 1];
nodes[n - i - 1] = NULL;
for (j = 1; j < n - i - 1; j++) {
nodes[j] = nodes[j + 1];
}
}
}
void generateHuffmanCodes(node *root, int depth, char code[], char huffmanCodes[][100]) {
if (root->left == NULL && root->right == NULL) {
阅读全文