学习了几周,玩得很开心。
学习java的第一件事就是做一个程序生成Huffman编码。
在这里我学会了LinkedList的使用,它可以保存任何类型的对象。
如下是我的编码结构体
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package HuffmanTree;
import java.io.Serializable;
/**
*
* @author sys
*/
public class HuffmanPoint implements Serializable
{
public char Letter = ' ';
public int Number = 0;
public int father = -1, lchild = -1, rchild = -1;
public StringBuffer HuffmanCode= new StringBuffer();
public void print()
{
System.out.println(Letter + " 哈弗曼编码是: "+ HuffmanCode );
}
}
再下面是生成Huffman编码的类
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package HuffmanTree;
import java.util.*;
/**
*
* @author SKUSR
*/
public class HuffmanLink
{
public LinkedList Link(LinkedList HuffmanArray) //生成哈弗曼树
{
try
{
int size = HuffmanArray.size();
int linksize = 2*size - 1;
for(int i=size; i<linksize; i++)//生成哈弗曼树
{
int addr[] = Select(HuffmanArray,i-1);
HuffmanPoint Huffmanlchild = (HuffmanPoint)HuffmanArray.get(addr[0]);
HuffmanPoint Huffmanrchild = (HuffmanPoint)HuffmanArray.get(addr[1]);
Huffmanlchild.father = i;
Huffmanrchild.father = i;
HuffmanPoint Huffmanfather = new HuffmanPoint();
Huffmanfather.Number = Huffmanlchild.Number + Huffmanrchild.Number;
Huffmanfather.lchild = addr[0];
Huffmanfather.rchild = addr[1];
HuffmanArray.add(Huffmanfather);
}
for(int i = linksize-2; i>=0; i--)//从倒数第2个节点开始生成赫夫曼编码
{
HuffmanPoint HuffmanTemp = (HuffmanPoint)HuffmanArray.get(i);
HuffmanPoint Huffmanfather = (HuffmanPoint)HuffmanArray.get(HuffmanTemp.father);
HuffmanTemp.HuffmanCode.append(Huffmanfather.HuffmanCode);//子节点的赫夫曼编码只是在父亲的基础上加一个0或者1
if(Huffmanfather.lchild == i)
{
HuffmanTemp.HuffmanCode.append('0');
}
else
{
HuffmanTemp.HuffmanCode.append('1');
}
}
for(int i = linksize-1; i>=size; i--)//删除创建赫夫曼数时创建的元素
{
HuffmanArray.remove(i);
}
/*
for (int i = 0; i<size; i++)
{
HuffmanPoint HuffmanTemp = (HuffmanPoint)HuffmanArray.get(i);
System.out.println("编号:" + HuffmanTemp.Letter + " 赫夫曼编码是:" + HuffmanTemp.HuffmanCode);
}
*/
}
catch(Exception ex)
{
System.out.print(ex);
}
return HuffmanArray;
}
private int[] Select(LinkedList HuffmanArray, int Addr)
{
int[] Small = {100000,100000};
int[] Where = {0,1};
for(int i = 0; i<=Addr; i++)
{
HuffmanPoint HuffmanTemp = (HuffmanPoint)HuffmanArray.get(i);
if(HuffmanTemp.father == -1)
{
if(HuffmanTemp.Number < Small[0])
{
Small[1] = Small[0];
Where[1] = Where[0];
Small[0] = HuffmanTemp.Number;
Where[0] = i;
}
else if(HuffmanTemp.Number < Small[1])
{
Small[1] = HuffmanTemp.Number;
Where[1] = i;
}
}
}
return Where;
}
}