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

📄 sethuff.cpp

📁 使用vc++编写的一个实现huffman编码的程序
💻 CPP
字号:
#include"Sethuff.h"
#include"Huffcode.h"
#include<fstream.h>
#include<iostream.h>
Sethuff::Sethuff(unsigned int n,unsigned int *num,char *charn)
	{
	   Huffcode *q;	   
       cha=charn;
	   table=num;
	   N=n;
	   hcode=new Huffcode(table[0],cha[0]);
       root=q=hcode;
	  for(int i=1;i<N;i++)
	  {
		  root=new Huffcode(table[i],cha[i]);
		  q->left=root;
		  root->right=q;
		  q=root;
	  }
	  for(int j=N;j<2*N-1;j++)
	  {
		  root=new Huffcode(0);
		  q->left=root;
		  root->right=q;
		  q=root;
	  }
	  q=hcode;
	  while(q->weight!=0)
	  {
		  cout<<q->weight<<"个"<<q->Hnode<<" || ";
		  q=q->left;
	  }
	  cout<<endl;
	}
////////////////////////////////////////////////
void Sethuff::Setting()
{
		Huffcode *w,*min1,*min2;
		w=hcode;
		while(w->weight!=0)
		{
			w=w->left;
		}
	for(int k=0;k<N-1;k++)
	{
		min1=Sorting();		
		min1->parent=w;
		w->lchild=min1;
		min2=Sorting();
		min2->parent=w;
		w->rchild=min2;
		w->weight=min1->weight+min2->weight;
		w=w->left;
	} 
}
////////////////////////////////////////////////
Huffcode *Sethuff::Sorting()
	{
		Huffcode *p,*min;
        min=hcode;
        p=min->left;
        while(p->weight!=0)
        {   
            if(p->weight<min->weight) //比较,min记住最小值位置
            {            		
                min=p;
            }             
            p=p->left;
        } 
		if(min==hcode)
		{
			hcode=hcode->left;
			min->left=NULL;
		}
		else
		{
			min->left->right=min->right;
			min->right->left=min->left;
			min->left=NULL;
			min->right=NULL;
		}
	return min;
	}
////////////////////////////////////////////////////////
void Sethuff::inorder(char aa)
	{
		char bb;
		bb=aa;
       inorder(root,bb);
	}
void Sethuff::inorder(Huffcode *p,char aa)
	{
		ofstream out(".\\code.txt",ios::ate);
		int i=0;
		Huffcode *q;
		if(p!=NULL)
		{
			if(p->Hnode==aa)
			{
				out<<p->Hnode<<"   ";
				cout<<p->Hnode<<"  ";
			    q=p;
				while(q->parent!=NULL)
				{
					if(q->parent->lchild==q)
						code[i]='0';
					if(q->parent->rchild==q)
						code[i]='1';
					q=q->parent;
					i++;
				}			
			for(int ii=i-1;ii>=0;ii--)
			{
				out<<code[ii];
				cout<<code[ii];
			}
			cout<<endl;
			out<<endl;
			}
			
			inorder(p->lchild,aa);
		    inorder(p->rchild,aa);
		}		
	}
////////////////////////////////////////////////
void Sethuff::explain(char *ch)
{
	ofstream out(".\\data.txt",ios::ate);
	Huffcode *q,*p;
	p=q=root;
	int i=0;
    len=strlen(ch); 
	if(ch==NULL);
	else
	{
  for(i;i<len;i++)
  {
	if(ch[i]=='0')
	{
	 p=p->lchild;
	}
	if(ch[i]=='1')
	{
	 p=p->rchild;
	}
	if(p->Hnode!=NULL)
	{
      cout<<p->Hnode;
	  out<<p->Hnode;
	  p=root;
	}
  } 
  out<<endl;
  cout<<endl;
  cout<<"解码文件已存入'data.txt'文档!"<<endl;
	}
}

⌨️ 快捷键说明

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