哈夫曼编码
程序代码
import java.util.Scanner;
import java.util.LinkedList;
import java.util.Collections;
public class Huffman {
private static LinkedList<HuffmanNode> huffmanList =
new LinkedList<>();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入待编码的节点个数:");
int n = input.nextInt();
System.out.println("请输入节点的内容及其频数:");
for(int i = 0; i < n; i++) {
String s = input.next();
int v = input.nextInt();
huffmanList.add(new HuffmanNode(v, s));
}
huffCode();
decode(huffmanList.get(0), "");
}
public static void huffCode() {
if(huffmanList.size() == 1) {
return;
}
while(huffmanList.size() > 1) {
Collections.sort(huffmanList);
HuffmanNode node = new HuffmanNode(huffmanList.get(0),
huffmanList.get(1));
huffmanList.remove();
huffmanList.remove();
huffmanList.add(node);
}
}
public static void decode(HuffmanNode h, String code) {
if(h.lChild == null && h.rChild == null)
{
System.out.println("元素 " + h.name + "的编码为:" + code);
return;
}
decode(h.lChild, code + "0");
decode(h.rChild, code + "1"); D
}
}
class HuffmanNode implements Comparable<HuffmanNode> {
int value;
String name;
HuffmanNode lChild = null;
HuffmanNode rChild = null;
public HuffmanNode() {
}
public HuffmanNode(int v,String s) {
value = v;
name = s;
}
public HuffmanNode(HuffmanNode l,HuffmanNode r) {
lChild = l;
rChild = r;
value = lChild.value + rChild.value;
}
@Override
public int compareTo(HuffmanNode node1) {
if (value<node1.value) {
return -1;
}
else if (value == node1.value) {
return 0;
}
else {
return 1;
}
}
}
运行结果