Haffman编码/译码——数据结构作业(二)

本文探讨了使用Huffman算法进行编码和解码的实践,涉及深度优先搜索(DFS)策略。在数据结构中,利用队列和Huffman树进行操作。文章提到了构建Huffman树时,虽然可以采用链表,但数组在存储和操作上更为便捷。
摘要由CSDN通过智能技术生成

算法:Haffman,DFS
数据结构:queue,Haffman Tree

PS:使用链表建树,但用数组存树操作更方便

// Huffman.cpp : 定义控制台应用程序的入口点。
//

//#include "stdafx.h"

#include "iostream"
#include "stdio.h"
#include "stdlib.h" 
#include "string.h"
#include "string"
#include "queue"
#include "fstream"
const int max_nodenum=100;         //最多字符数 
using namespace std;

struct Node
{
    char ch;
    double weight;
    Node* parent;
    Node* Lchild;
    Node* Rchild;
    Node()
    {
        ch = NULL;
        weight = 0;
        parent = NULL;
        Lchild = NULL;
        Rchild = NULL;
    }
    bool operator < (const Node &a)const   
    {
        return a.weight < weight;
    }
}Hf[max_nodenum];   //Hf[n]用来存储符号信息,和建树无关

struct Info              //打表保存字符编码信息
{
    char ch;
    string code;
}info[max_nodenum];

Node *root;           //huffman树根

void CreateTree()
{
    root = new Node;
    priority_queue <Node> Queue;
    ifstream fin("hfmTree.txt");      //在文件中读取已保存的数据
    int n;
    fin >> n;
    for (int i = 0; i < n; i++)
    {
        fin >> Hf[i].ch >> Hf[i].weight;       
        Queue.push(Hf[i]);
    }
    while (Queue.size() > 1)                     //建树 从下向上
    {
        Node* a = new Node;                      //左子树
        if (Queue.top().ch == NULL)
        {
            *a = Queue.top();
            a->Lchild->parent = a;                  //***被坑了好久
            a-
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值