英文字符串哈夫曼编码的C语言实现

数据结构课的实验报告···

具体思路是用一个最小堆去储存所有哈夫曼的节点,然后每次从堆中弹出两个哈夫曼节点组成新节点,然后将这个新节点加入原来的最小堆,循环往复后最后将哈夫曼树的根节点弹出。代码实现如下:

//
//  main.c
//  HuffTree
//
//
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct HfTreeNode *HfTree;
typedef struct HNode *Heap;
struct HNode    {
    HfTree *Data;
    int Size;
    int Capacity;
};
struct HfTreeNode   {
    char ch;
    int weight;
    HfTree Left;
    HfTree Right;
};

void PrintCode(HfTree root,int *arr,int top);
void PrintArr(int *arr,int top);

HfTree DeleteMin( Heap H );
Heap CreateHeap(int size);
void Adjust(Heap H, int p);
void BuildHeap(Heap H);


Heap Read(void);


HfTree Huffman(Heap heap);
int main(int argc, const char * argv[]) {
    int arr[100]={0},top=0;
    HfTree Root;
    Heap heap;
    heap=Read();
    Root=Huffman(heap);
    PrintCode(Root, arr, top);
    return 0;
    }
Heap Read(void)  {
    int num=0,dataNum=1;
    int frequency[58]={0};//用于统计次数的数组
    Heap heap;

    char c;
    while((c=getchar())!='\n')  {
        frequency[c-65]++;
    }
    for (int i=0; i<58; i++) {
        if(frequency[i]!=0)
            num++;
    }//找出输入的有效字母数量
    
    heap=CreateHeap(num);//建堆
    
    for (int i=0; i<58; i++) {
        //找到有效字母
        if(frequency[i]!=0) {
            //放入节点的过程
            HfTree p=(HfTree)malloc(sizeof(struct HfTreeNode));
            p->Left=NULL;
            p->Right=NULL;
            p->weight=frequency[i];
            p->ch=i+65;
            heap->Data[dataNum++]=p;
            heap->Size++;
        }
    }
    return heap;
}
Heap CreateHeap(int MaxSize)   {
    HfTree p=(HfTree)malloc(sizeof(struct HfTreeNode));
    p->Left=NULL;
    p->Right=NULL;
    p->weight=-1;
    /*
     设置哨兵
     */
    Heap H = (Heap)malloc(sizeof(struct HNode));
    H->Data = (HfTree *)malloc((MaxSize+1)*sizeof(struct HfTreeNode));//data存储的是指向HfTree的指针
    H->Size = 0;//初始化堆的大小为0
    H->Capacity = MaxSize;//设定堆的容量
    /*
     将除data的指针全设为NULL
     */
    for(int i=0;i<=MaxSize;i++)
        H->Data[i]=NULL;
    H->Data[0]=p;//设置哨兵
    return H;
}



void Insert( Heap H, HfTree X ) {
    int i=++H->Size;
    for (; H->Data[i/2]->weight>X->weight; i/=2 )
        H->Data[i] = H->Data[i/2];
    H->Data[i] = X;
}
HfTree Huffman(Heap heap)   {
    BuildHeap(heap);
    HfTree p;
    for (int i=1; i<heap->Capacity; i++) {
        p=(HfTree)malloc(sizeof(struct HfTreeNode));
        p->Left=DeleteMin(heap);
        p->Right=DeleteMin(heap);
        p->weight=p->Left->weight+p->Right->weight;
        Insert(heap, p);
    }
    p=DeleteMin(heap);
    return p;
}
void Adjust(Heap H, int p)    {
    int Parent, Child;
    HfTree X;
    X = H->Data[p];
    for( Parent=p; Parent*2<=H->Size; Parent=Child ) {
        Child = Parent * 2;
        if( (Child!=H->Size) && (H->Data[Child]->weight>H->Data[Child+1]->weight) )
            Child++;
        if( X->weight <= H->Data[Child]->weight ) break;
        else
            H->Data[Parent]= H->Data[Child];
    }
    H->Data[Parent] = X;
}
void BuildHeap( Heap H )    {
    /*
     从最后一个节点的父节点开始将一个子单元调整成堆,不断循环直到所有都调成堆
     */
    for(int i = H->Size/2; i>0; i-- )
        Adjust(H, i);
}
HfTree DeleteMin(Heap H)  {
    int Parent, Child;
    HfTree MinItem, X;
    MinItem = H->Data[1];
    X = H->Data[H->Size--];
    for( Parent=1; Parent*2<=H->Size; Parent=Child ) {
        Child = Parent * 2;
        if( (Child!=H->Size) && (H->Data[Child]->weight>H->Data[Child+1]->weight) )
            Child++;
        if( X->weight <= H->Data[Child]->weight ) break;
        else
            H->Data[Parent]= H->Data[Child];
    }
    H->Data[Parent] = X;
    
    return MinItem;
}



void PrintCode(HfTree tree,int *arr,int top)    {
    if (tree->Left) {
        arr[top] = 0;
        PrintCode(tree->Left, arr, top + 1);
    }
    if (tree->Right) {
        arr[top] = 1;
        PrintCode(tree->Right, arr ,top + 1);
    }
    // 如果是叶节点就打印
    if (tree->Left==NULL&&tree->Right==NULL) {
        printf("%c:", tree->ch);
        PrintArr(arr, top);
    }
}
void PrintArr(int *arr,int top) {
    for (int i = 0; i < top; ++i)
        printf("%d", arr[i]);
    printf("\n");
}

 

这里提供一个使用哈希表统计字符串出现次数的C语言示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_HASH_TABLE_SIZE 100 // 哈希表的最大长度 typedef struct node { char* key; // 键值 int value; // 出现次数 struct node* next; // 指向下一个节点的指针 } Node; Node* hashTable[MAX_HASH_TABLE_SIZE]; // 哈希表 int tableSize = 0; // 实际哈希表的长度 // 哈希函数 int hash(char* key) { int hashValue = 0; while (*key != '\0') { hashValue = (hashValue << 5) + *key++; // 每个字符左移5位再相加 } return hashValue % MAX_HASH_TABLE_SIZE; } // 插入一个节点到哈希表中 void insert(char* key) { int index = hash(key); Node* ptr = hashTable[index]; while (ptr != NULL) { if (strcmp(ptr->key, key) == 0) { // 如果找到了相同的键值,增加出现次数 ++ptr->value; return; } ptr = ptr->next; } // 如果没有找到相同的键值,创建一个新的节点并插入到链表头部 Node* newNode = (Node*)malloc(sizeof(Node)); newNode->key = key; newNode->value = 1; newNode->next = hashTable[index]; hashTable[index] = newNode; ++tableSize; } // 遍历哈希表,输出统计结果 void printHashTable() { printf("Result (key, value):\n"); for (int i = 0; i < MAX_HASH_TABLE_SIZE; ++i) { Node* ptr = hashTable[i]; while (ptr != NULL) { printf("('%s', %d)\n", ptr->key, ptr->value); ptr = ptr->next; } } } int main() { // 读入字符串 char str[100]; printf("Please input the string:\n"); fgets(str, sizeof(str), stdin); str[strlen(str)-1] = '\0'; // 去掉换行符 // 把字符串按照空格分割成多个单词 char* word = strtok(str, " "); while (word != NULL) { insert(word); word = strtok(NULL, " "); } printHashTable(); return 0; } ``` 关于哈夫曼编码,可以参考下面的C语言示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_NODE_NUM 200 // 最大节点数 #define MAX_CODE_LEN 100 // 最大编码长度 // 哈夫曼树的节点 typedef struct node { int weight; // 权值 int parent, lchild, rchild; // 指向父节点和左右子节点的指针 } HNode; // 编码表的一个项 typedef struct code { char data; // 字符 char code[MAX_CODE_LEN]; // 对应的哈夫曼编码 } HCode; // 创建哈夫曼树 void createHuffmanTree(HNode* tree, int n) { for (int i = 0; i < 2*n-1; ++i) { tree[i].parent = -1; tree[i].lchild = -1; tree[i].rchild = -1; } for (int i = 0; i < n; ++i) { printf("Please input the weight of node %d:\n", i+1); scanf("%d", &(tree[i].weight)); } for (int i = n; i < 2*n-1; ++i) { int s1 = -1, s2 = -1; // 找到权值最小的两个节点 for (int j = 0; j < i; ++j) { if (tree[j].parent == -1) { if (s1 == -1 || tree[j].weight < tree[s1].weight) { s2 = s1; s1 = j; } else if (s2 == -1 || tree[j].weight < tree[s2].weight) { s2 = j; } } } tree[s1].parent = i; tree[s2].parent = i; tree[i].lchild = s1; tree[i].rchild = s2; tree[i].weight = tree[s1].weight + tree[s2].weight; } } // 从叶子节点遍历哈夫曼树,生成编码表 void createHuffmanCode(HNode* tree, HCode* hcodes, int n) { char buffer[MAX_CODE_LEN]; // 缓冲区 for (int i = 0; i < n; ++i) { int current = i; int parent = tree[current].parent; int codeLen = 0; while (parent != -1) { // 遍历到根节点 if (tree[parent].lchild == current) { // 左子节点,则在编码前面添加0 buffer[codeLen++] = '0'; } else if (tree[parent].rchild == current) { // 右子节点,则在编码前面添加1 buffer[codeLen++] = '1'; } current = parent; parent = tree[current].parent; } buffer[codeLen] = '\0'; hcodes[i].data = (char)(i+1); // 字符,这里设为i+1 strcpy(hcodes[i].code, strrev(buffer)); // 将缓冲区中的0和1翻转,得到正确的编码 } } int main() { // 创建哈夫曼树 HNode* tree = (HNode*)malloc(MAX_NODE_NUM * sizeof(HNode)); printf("Please input the number of leaf nodes:\n"); int n; scanf("%d", &n); createHuffmanTree(tree, n); // 生成哈夫曼编码 HCode* hcodes = (HCode*)malloc(n * sizeof(HCode)); createHuffmanCode(tree, hcodes, n); // 输出编码表 printf("Huffman coding table:\n"); for (int i = 0; i < n; ++i) { printf("%c: %s\n", hcodes[i].data, hcodes[i].code); } return 0; } ``` 注意:这里用到了一个strrev()函数,请自行实现
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值