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

📄 coding_decode.h

📁 这是一个霍夫曼编码解码的源程序,可以用它高效实现霍夫曼解码编码,注释详细,可读性好.压缩包止包括源程序文件,再vc中运行.
💻 H
字号:
#include<iostream.h>
#include"huffman.h"
class huffcode//存放字符及相应的编码
{
public:
	char keyc;
	char hufc[30];
};  
huffcode * coding(binTree *tree,int L)//编码程序
{
	huffcode *hc=new huffcode[L];
    element *current=tree->root;
	element *currentFront=current;//currentFront用于指向当前结点的父母
	int j=0;
	for(int i=0;i<L;i++)
	{  
	   j=0;
	   currentFront=current=tree->root;
       while(1)
	   {  
		   if(current->leftchild->mark==0)//mark等于0说明当前结点的左子树的叶子还没有扫描完,继续扫描
		   {
			 //cout<<"current->data.key="<<current->data.key<<endl;
			 hc[i].hufc[j]='0';//记下路径,往左为0,往右为1
			 j++; 
			 if(current->leftchild->leftchild==NULL) 
			 {  
                 hc[i].hufc[j]='\0';
				 hc[i].keyc=current->leftchild->data.keymark;
                 current->leftchild->mark=1;
				 break;	
			 }
			 currentFront=current;
			 current=current->leftchild;
		   }
	  	  if(current->leftchild->mark==1)//mark等于0说明当前结点的左子树的叶子已经扫描完,扫描右子树
		  {   
			   //cout<<"current->data.key="<<current->data.key<<endl;
			   hc[i].hufc[j]='1';//记下路径,往左为0,往右为1
			   j++;
			   if(current->rightchild->leftchild==NULL) 
			   {
                 hc[i].hufc[j]='\0';    
				 hc[i].keyc=current->rightchild->data.keymark;
                 current->rightchild->mark=1;
				 current->mark=1;
                 while((currentFront->leftchild->mark==1)&&(currentFront->rightchild->mark==1))//扫描完当前结点的右子树,需要往上标记mark
				 {
				   currentFront->mark=1;
				   if(currentFront==tree->root) break;
				   if(currentFront->parent->parent!=NULL)
				   {
					   //cout<<currentFront->data.key<<endl;
					   currentFront=currentFront->parent; 
				   }
				   else
					   break;
				 }/**/	 
				 break;
			   }
               currentFront=current;//指向当前结点的父母
			   current=current->rightchild;
		  }
	   }
	}
	return hc;
}
void decode(binTree *tree,char c[])//解码程序
{
	element *current=tree->root;
	for(int i=0;i<strlen(c);i++)
	{
       
		if(c[i]=='0')  current=current->leftchild;//如果是0,指向左子女
		else
		{
	      if(c[i]=='1')  current=current->rightchild;//如果是1,指向左子女
		  else 
			cout<<"你输入的报文有误!报文必须由二进制位组成!";//不能出现0,1以外的字符,否则警告
		}
		if(current->leftchild==NULL)//到达叶子,则译出一个字符
		{
		  cout<<current->data.keymark;
		  current=tree->root;
		}
	}
}

⌨️ 快捷键说明

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