最近有点忙,姑且先放上有注释的代码,有时间再来补充一些技术细节吧
/**
*
*/
/**
* @author 32809
*
*/
package haff;
public class node {
node left;
node right;
int num;
char key;//新建链表
public void node() {
left = null;
right = null;
key = ' ';//创建节点
}
private void printCode(node node, String string) {
if (node.left != null) {
printCode(node.left, string + 0);
}
if (node.right != null) {
printCode(node.right, string + 1);//左节点+0,右节点+1,不得不说java在这方面比c++好用多了
}
if (node.left == null && node.right == null
//&& node.key != ' '
) {
System.out.println(node.key + "\t" + string + "\t" + node.num);
}
}
public static void main(String[] argv) {
String b = "aaaabcc";//测试字符串
node count2[] = new node[256];
int t = 0;
for (int i = 0; i < 256; i++) {
count2[i] = new node();
}//为二百五十六种as码的的字符设置空间
for (int i = 0; i < b.length(); i++) {
for (int j = 0; j <= 256; j++) {
if (j == 256) {
count2[t].key = b.charAt(i);
count2[t].num = 1;
t++;//之前没有该字符则创建该字符
} else {
// System.out.println(b.charAt(i));
if (count2[j].key == b.charAt(i)) {
count2[j].num++;
break;
}//已有该字符则计数
}
}
}
node count[]=new node[t];
for(int i=0;i<t;i++)count[i]=count2[i];
for (int i = 0; i < count.length-1; i++) {
for (int j = 0; j < count.length-i; j++) {
for (int k = j; k < count.length - i - 1; k++) {
if (count[k].num < count[k + 1].num) {
node tran = new node();
tran = count[k];
count[k] = count[k + 1];
count[k + 1] = tran;//冒泡排序
}
}
}
if(i<count.length-2)
{
node ne = new node();
ne.left = count[count.length - i-1];
ne.right = count[count.length-2 - i];
ne.num = count[count.length - i - 2].num + count[count.length - i-1].num;
ne.key = ' ';
count[count.length - i - 2] = ne;
}//实现哈夫曼树
else
{
node ne = new node();
ne.left=count[0];
ne.right=count[1];
count[0]=ne;
}
}
node ne = count[0];
ne.key=' ';
String ans = " ";
ne.printCode(ne, ans);//打印结果
}
}