| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 492 人关注过本帖
标题:求助,为什么我的哈夫曼编码输出有误,帮帮忙!
只看楼主 加入收藏
hy247767221
Rank: 2
来 自:襄樊
等 级:论坛游民
帖 子:41
专家分:22
注 册:2011-7-27
结帖率:87.5%
收藏
 问题点数:0 回复次数:1 
求助,为什么我的哈夫曼编码输出有误,帮帮忙!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define  n  5
#define  m  n*2-1

typedef struct Haffman
{
    int weight;
    int lchild, rchild, parent;
}Haffmantree[n];

typedef struct Code
{
    char ch;
    char bits[n];
}Haffmancode[m];

void Create_haffmantree(Haffmantree t);
void Haffman_code(Haffmantree t, Haffmancode h);

int main()
{
    Haffmantree t;
    Haffmancode h;

    Create_haffmantree(t);

    Haffman_code(t, h);

    putchar(10);
    return 0;
}
//构造哈夫曼二叉树
void Create_haffmantree(Haffmantree t)
{
    int i, j, p1, p2;
    int min1 = -1, min2 = -1;

    for(i = 0; i < m; i ++)
    {
        t[i].weight = 0;
        t[i].lchild = t[i].rchild = t[i].parent = 0;
    }

    for(i = 0; i < n; i ++)
    {
        printf("Please input the No.%d weight: ", i + 1);
        scanf("%d", &t[i].weight);
    }

    putchar(getchar());   //解除换行占位的影响

    for(j = 0; j < n - 1; j ++)
    {
        for(i = 0; i < n + j; i ++)
        {
            if(t[i].parent == 0)
            {
                if(t[i].weight < min1 || min1 == -1)
                {
                    if(min1 != -1)
                    {
                        min2 = min1;
                        p2 = p1;
                    }
                    min1 = t[i].weight;
                    p1 = i;
                }
                else if(t[i].weight < min2 || min2 == -1)
                {
                    min2 = t[i].weight;
                    p2 = i;
                }
            }
        }
        t[p1].parent = t[p2].parent = n + j;
        t[n + j].lchild = p1;
        t[n + j].rchild = p2;
        t[n + j].weight = t[p1].weight + t[p2].weight;
    }
}
//构造哈夫曼编码
void Haffman_code(Haffmantree t, Haffmancode h)
{
    int i;
    int p, c;
    int start;
    char cd[n + 1];

    cd[n] = '\0';
    printf("Please int the character:");
    for(i = 0; i < n; i ++)
    {
        start = n;
        h[i].ch = getchar();
        c = i;
        p = t[i].parent;
        while(p != 0)
        {
            -- start;
            if(t[p].lchild == c)
                cd[start] = '0';
            else
                cd[start] = '1';
            c = p;
            p = t[c].parent;
        }
        strcpy(h[i].bits, &cd[start]);
    }

    putchar(10);
    for(i = 0; i < n; i ++)
        printf("No.%d character %c's coding is %s \n", i + 1, h[i].ch, h[i].bits);
}
搜索更多相关主题的帖子: include parent 
2011-11-24 11:14
孙咸胜
Rank: 1
来 自:集合
等 级:新手上路
帖 子:5
专家分:0
注 册:2021-12-19
收藏
得分:0 
输出没有错误,但是你这代码有问题,
2021-12-29 14:59
快速回复:求助,为什么我的哈夫曼编码输出有误,帮帮忙!
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.034531 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved