// Source code example for "A Practical Introduction // to Data Structures and Algorithm Analysis" // by Clifford A. Shaffer, Prentice Hall, 1998. // Copyright 1998 by Clifford A. Shaffer /* Huffman coding tree Main program. First, read from the data file a set of strings and associated frequencies. These are placed onto a list of (single node) Huffman trees. Next, build a single Huffman coding tree for the set. The strings and their codes are then output, with CodeTable storing the coding for each input string. Next, read commands to "encode" or "decode" strings, providing the appropriate output. */ import java.io.*; import java.util.*; public class Huffmain { private static Vector codeTable = new Vector(); // The code lookup table private static int total = 0; // Total weight of codes // Read a list of strings and frequencies, // creating initial list of Huffman coding tree nodes static void readFreqs(DataInputStream d, List hufflist) throws IOException { String line; char letter; int freq; HuffTree temptree; while((line = d.readLine()) != null) { // process the entry, creating a new HuffTree if (line.substring(0, 3).equals("end")) return; // Done with frequencies letter = line.charAt(0); freq = Integer.parseInt(line.substring(2)); temptree = new HuffTree(new LettFreq(freq, letter)); // Put in the list in sorted order // WARNING: This may be considered buggy. Nodes with equal // weight will be put in reverse order of appearance, not // in alphabetical order. for (hufflist.setFirst(); hufflist.isInList(); hufflist.next()) if (temptree.weight() <= ((HuffTree)hufflist.currValue()).weight()) { hufflist.insert(temptree); break; } if (!hufflist.isInList()) hufflist.append(temptree); } } // Build a Huffman tree from list hufflist static HuffTree buildTree(List hufflist) { HuffTree temp1, temp2, temp3; LettFreq tempnode; for(hufflist.setPos(1); hufflist.isInList(); hufflist.setPos(1)) { // While at least two items left hufflist.setFirst(); temp1 = (HuffTree)hufflist.remove(); temp2 = (HuffTree)hufflist.remove(); tempnode = new LettFreq(temp1.weight() + temp2.weight()); temp3 = new HuffTree(tempnode, temp1, temp2); // return to the list in sorted order for (hufflist.setFirst(); hufflist.isInList(); hufflist.next()) if (temp3.weight() <= ((HuffTree)(hufflist.currValue())).weight()) { hufflist.insert(temp3); break; } // Put in list if (!hufflist.isInList()) // It is heaviest value hufflist.append(temp3); } hufflist.setFirst(); // Tree now only element on list return (HuffTree)hufflist.remove(); // Return the tree } // Find the index in CodeTable for the given codeword static int getindex(char codeword) { int i; for (i=0; i