# 数据结构-哈夫曼(Huffman)

208人阅读 评论(0)

#include <iostream>
#include <cstdio>
#include <malloc.h>
#define LIST_INIT_SIZE 10
#define LISTINCREMENT 100
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define MAX 0xcfcfcfcf
using namespace std;

typedef struct
{
unsigned int weight;
unsigned int parent, lchild, rchild;
} HTNode, *HUffmanTree;
void select(HUffmanTree HT, int n, int *s1, int *s2);
void found(HUffmanTree ht, int i, int j, char *c);
void HUffmanCoding(HUffmanTree *HT, int *w, int n);

int main()
{
char c[10];
int w[10] = {5,29,7,8,14,23,3,11};
HUffmanTree HT;
HUffmanCoding(&HT,w,8);//8是数组长度
for(int i=0; i<8; i++) printf("%d%c",w[i],i==7?'\n':' ');
found(HT,14,0,c);//14是树根所在位置
return 0;
}

void select(HUffmanTree HT, int n, int *s1, int *s2)
{
unsigned int min1, min2;
min1 = min2 = MAX;
for(int i = 0; i < n; i++)
{
if(HT[i].weight <= min1&& !HT[i].parent)
{
min2 = min1;
*s2 = *s1;
min1 = HT[i].weight;
*s1 = i;
}
else if(HT[i].weight < min2&& !HT[i].parent)
{
min2 = HT[i].weight, *s2 = i;
}
}
}

void found(HUffmanTree ht, int i, int j, char *c)
{
if(ht[i].lchild==0 && ht[i].rchild==0)
{
c[j] = '\0';
printf("i:%-2d w:%-2d char:%s\n", i, ht[i].weight, c);
return;
}
c[j] = '1';
found(ht,ht[i].lchild,j+1,c);
c[j] = '0';
found(ht,ht[i].rchild,j+1,c);
return;
}

void HUffmanCoding(HUffmanTree *HT, int *w, int n)
{
int s1, s2;
if(!n) return;
*HT = (HUffmanTree)malloc((2*n)*sizeof(HTNode));
HUffmanTree p = *HT;
for(int i = 0; i< n; i++)
{
p[i].lchild = p[i].rchild = p[i].parent = 0;
p[i].weight = w[i];
}
for(int i =n; i < 2*n; i++)
{
p[i].weight = p[i].lchild = p[i].rchild = p[i].parent = 0;
}
for(int i = n; i < 2*n-1; i++)
{
select(*HT, i, &s1, &s2);
p[s1].parent = i, p[s2].parent = i;
p[i].lchild = s1, p[i].rchild = s2;
p[i].weight = p[s1].weight + p[s2].weight;
}
printf("Weight parent lchild rchild\n");
for(int i = 0; i < 2*n-1; i++)
printf("   %-4d  %-4d   %-4d   %-4d\n",p[i].weight, p[i].parent, p[i].lchild, p[i].rchild);
printf("----------------------------------\n");
return;
}



0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：9819次
• 积分：438
• 等级：
• 排名：千里之外
• 原创：34篇
• 转载：3篇
• 译文：0篇
• 评论：2条
文章分类
评论排行