tree[i].rchild=-1; tree[i].weight=0; }
for(i=0;i
. . .
tree[i].ch=ch[i]; tree[i].weight=sum[i]; }
for(i=n;i
p1=0;p2=0;
small1=10000;small2=100; for(j=0;j
small2=small1;
small1= tree[j].weight; p2=p1; p1=j; } else
if(tree[j].weight
small2=tree[j].weight; p2=j; }
tree[p1].parent=i;
tree[p2].parent=i; tree[i].lchild=p1; tree[i].rchild=p2;
tree[i].weight=tree[p1].weight+tree[p2].weight; }
int c,p; //编码部分
Code=new Codetype[n]; for(i=0;i
. . Code[i]=new Codetype(); Code[i].bits=new Character[n];
.
}
for(i=0;i
Code[i].start=n; Code[i].ch=tree[i].ch; c=i;
p=tree[i].parent; while(p!=0) {
Code[i].start--; if(tree[p].lchild==c)
Code[i].bits[Code[i].start]='0'; else
Code[i].bits[Code[i].start]='1'; c=p;
p=tree[p].parent; }
Code[i]=Code[i];
}
System.out.println(\每种字符的编码结果如下:\ for(i=0;i
System.out.print(Code[i].ch+\ for(int r=Code[i].start;r
System.out.print(Code[i].bits[r]);
System.out.println(\ }
FileWriter fw=new FileWriter(\编码文件.txt\ for(int k=0;k
for(int l=0;l
if(a[k]==Code[l].ch){
for(int h=Code[l].start;h
String bm=Code[l].bits[h].toString();
fw.write(bm);
}
}}
fw.close();
File file1=new File(\编码文件.txt\
FileReader fr1=new FileReader(file1);
char[] b=new char[(int)file1.length()];//将编码后的文件读入
数组b[]
fr1.read(b); fr1.close(); int t=b.length;
p=m-1; //根节点
FileWriter fw1=new FileWriter(\译码文件.txt\ for(int q=0;q
if(b[q]=='0')
. . .
}
p=tree[p].lchild; else
p=tree[p].rchild; if(tree[p].lchild==-1)
{
String ym=tree[p].ch.toString(); fw1.write(ym); p=m-1;
}
}fw1.close();
}
Huffmantree类
public class Huffmantree {
public int weight;
public int parent,lchild,rchild; public Character ch; public Huffmantree(){ }}
weight=0; parent=0; lchild=-1; rchild=-1; ch='0';
codetype类
public class Codetype { }}
public Character bits[]; public int start; public char ch; public Codetype(){
start=0; ch=0;
结果和注释分别见测试结果和程序模块功能部分。
. . .
相关推荐: