/**
 * 
 */
import java.io.*;class Nodes {
int State; //whether has been sorted into one subtree
int RChild;
int LChild;
int Parent;
float Value;
}public class HufmanCoding { private int NodeNums; private Nodes[] NS = new Nodes[42]; public boolean Initial_Hufman() throws IOException {
System.out.println("Please input Node Numbers:");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String s = br.readLine();
NodeNums = Integer.parseInt(s);
} catch (Exception ep) {
System.out.println(" Node number Error!");
ep.printStackTrace();
return false;
} for (int i = 1; i <= NodeNums; i++) {
NS[i] = new Nodes();
System.out.println("Input the WEIGHT of " + i + " th node:");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String s = br.readLine();
NS[i].Value = Float.parseFloat(s);
} catch (Exception ep) {
System.out.println(" weight  Error!");
ep.printStackTrace();
return false;
}
NS[i].RChild = 0;
NS[i].LChild = 0;
NS[i].Parent = 0;
NS[i].State = 0;
}
for (int i = NodeNums + 1; i <= 2 * NodeNums - 1; i++) {
NS[i] = new Nodes();
NS[i].Value = 0;
NS[i].RChild = 0;
NS[i].LChild = 0;
NS[i].Parent = 0;
NS[i].State = 0;
} return true;
} public void Construct_Hufman() {
//choose a two least small nodes to construct the join the tree 
for (int out = 1; out <= NodeNums - 1; out++) {//out cycling NodeNums+1 times
int   lpos = 0;
int   rpos = 0;
float tmp2=2;
float tmp1=2;
for (int i = 1; i <= 2 * NodeNums - 1; i++)
if (NS[i].State == 0 && tmp1 >= NS[i].Value) {
lpos = i;
tmp1 = NS[i].Value;
} for (int i = 1; i <= 2 * NodeNums - 1 && i != lpos; i++)
if (NS[i].State == 0 && tmp2 >= NS[i].Value) {
rpos = i;
tmp2 = NS[i].Value;
} NS[lpos].Parent = NS[rpos].Parent = NodeNums + out; //to store the parent postion; NS[lpos].State = NS[rpos].State = 1; //sub nodes has been visited  NS[NodeNums + out].Value = NS[lpos].Value + NS[rpos].Value; //value is the sum of the two sub nodes NS[NodeNums + out].LChild = lpos; //record the left and the right child postion NS[NodeNums + out].RChild = rpos; }
} public void Print_Hufman() {
System.out.println("Next is the Tree:");
for (int i = 1; i <= 2 * NodeNums - 1; i++) {
System.out.println("Node" + "[" + i + "]");
System.out.println("Value:" + NS[i].Value);
System.out.println("RChild:" + NS[i].RChild);
System.out.println("LChild:" + NS[i].LChild);
System.out.println("Parent:" + NS[i].Parent);
System.out.println("State:" + NS[i].State); }
} public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
HufmanCoding HC = new HufmanCoding();
HC.Initial_Hufman();
HC.Construct_Hufman();
HC.Print_Hufman(); }}
运行错误:
Exception in thread "main" java.lang.NullPointerException
指示的是这一行:
NS[lpos].Parent = NS[rpos].Parent = NodeNums + out; //to store the parent postion;