⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 haffman.h

📁 哈夫曼编码器
💻 H
字号:
#define MaxValue 10000
#define Max 20
typedef struct
{
	int weight;
	int flag;
	int parent;
	int LeftChild;
	int RightChild;
}HaffNode;
typedef struct
{
	int weight;
	int start;
	int bit[Max];
}Code;
void Haffman(int weight[],int n,HaffNode haffTree[])
{
	int i,j,x1,x2,m1,m2;
	for(i=0;i<2*n-1;i++)
	{
		if(i<n) haffTree[i].weight=weight[i];
		else haffTree[i].weight=0;
		haffTree[i].parent=0;
		haffTree[i].flag=0;
		haffTree[i].LeftChild=-1;
		haffTree[i].RightChild=-1;
	}
	for(i=0;i<n-1;i++)
	{
		m1=m2=MaxValue;
		x1=x2=0;
		for(j=0;j<n+i;j++)
		{
			if(haffTree[j].weight<m1&&haffTree[j].flag==0)
			{
				m2=m1;
				x2=x1;
				m1=haffTree[j].weight;
				x1=j;
			}
			else
				if(haffTree[j].weight<m2&&haffTree[j].flag==0)
				{
					m2=haffTree[j].weight;
					x2=j;
				}
		}
		haffTree[x1].parent=n+i;
		haffTree[x2].parent=n+i;
		haffTree[x1].flag=1;
		haffTree[x2].flag=1;
		haffTree[n+i].weight=haffTree[x1].weight+haffTree[x2].weight;
		haffTree[n+i].LeftChild=x1;
		haffTree[n+i].RightChild=x2;
	}
}
void HaffmanCode(HaffNode haffTree[],int n,Code haffCode[])
{
	Code *cd=(Code*)malloc(sizeof(Code));
	int i,j,child,parent;
	for(i=0;i<n;i++)
	{
		cd->start=n-1;
		cd->weight=haffTree[i].weight;
		child=i;
		parent=haffTree[child].parent;
		while(parent!=0)
		{
			if(haffTree[parent].LeftChild==child)
				cd->bit[cd->start]=0;
			else
				cd->bit[cd->start]=1;
			cd->start--;
			child=parent;
			parent=haffTree[child].parent;
		}
		for(j=cd->start+1;j<n;j++)
			haffCode[i].bit[j]=cd->bit[j];
		haffCode[i].start=cd->start;
		haffCode[i].weight=cd->weight;
	}
}

				 





















⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -