c语言实现哈夫曼编码

要实现哈夫曼编码,需要以下步骤:

  1. 统计字符出现的频率
  2. 构建哈夫曼树
  3. 遍历哈夫曼树,给不同的字符赋予不同的编码
  4. 将编码后的字符写入文件中

下面是一个简单的 C 语言实现:

#include 
#include 
#include 

#define MAX_TREE_HT 100

// 节点结构体
struct MinHeapNode {
    char data; // 字符
    unsigned freq; // 频率
    struct MinHeapNode *left, *right; // 左右子节点
};

// 哈夫曼树结构体
struct MinHeap {
    unsigned size; // 大小
    unsigned capacity; // 容量
    struct MinHeapNode** array; // 数组
};

// 创建节点
struct MinHeapNode* newNode(char data, unsigned freq) {
    struct MinHeapNode* temp = (struct MinHeapNode*) malloc(sizeof(struct MinHeapNode));
    temp->left = temp->right = NULL;
    temp->data = data;
    temp->freq = freq;
    return temp;
}

// 创建一个大小为 capacity 的空的 MinHeap
struct MinHeap* createMinHeap(unsigned capacity) {
    struct MinHeap* minHeap = (struct MinHeap*) malloc(sizeof(struct MinHeap));
    minHeap->size = 0; // 初始化大小为 0
    minHeap->capacity = capacity;
    minHeap->array = (struct MinHeapNode**)malloc(minHeap->capacity * sizeof(struct MinHeapNode));
    return minHeap;
}

// 交换 *a 和 *b 的值
void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b) {
    struct MinHeapNode* temp = *a;
    *a = *b;
    *b = temp;
}

// 维护最小堆的特性
void minHeapify(struct MinHeap* minHeap, int idx) {
    int smallest = idx;
    int left = 2 * idx + 1;
    int right = 2 * idx + 2;
  
    if (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq)
        smallest = left;
  
    if (right < minHeap->size && minHeap->array[right]->freq < minHeap->array[smallest]->freq)
        smallest = right;
  
    if (smallest != idx) {
        swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);
        minHeapify(minHeap, smallest);
    }
}

// 检查大小为 1 的最小堆
int isSizeOne(struct MinHeap* minHeap) {
    return (minHeap->size == 1);
}

// 从 MinHeap 中取出最小的节点 (最小堆的根)
struct MinHeapNode* extractMin(struct MinHeap* minHeap) {
    struct MinHeapNode* temp = minHeap->array[0];
    minHeap->array[0] = minHeap->array[minHeap->size - 1];
    --minHeap->size;
    minHeapify(minHeap, 0);
    return temp;
}

// 插入新的节点到 MinHeap 中
void insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode) {
    ++minHeap->size;
    int i = minHeap->size - 1;
  
    while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) {
        minHeap->array[i] = minHeap->array[(i - 1) / 2];
        i = (i - 1) / 2;
    }

    minHeap->array[i] = minHeapNode;
}

// 判断当前节点是否是叶子节点
int isLeaf(struct MinHeapNode* root) {
    return !(root->left) && !(root->right);
}

// 创建并构建哈夫曼树
struct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size) {
    struct MinHeapNode *left, *right, *top;
  
    // 创建一个最小堆,并初始化大小
    struct MinHeap* minHeap = createMinHeap(size);
    for (int i = 0; i < size; ++i)
        minHeap->array[i] = newNode(data[i], freq[i]);
    minHeap->size

你可能感兴趣的:(c语言,算法,开发语言)