a5 programm22

profilesehj
FrequencyList.java

//The linked list of nodes containing frequency data class FrequencyList { Node head; int count; FrequencyList() { head = null; count = 0; } //search for node in linked list that contains key. Returns a reference to node if found, else returns null. public Node search(String key) { Node curr=head; while (curr != null) { if (key.compareTo(curr.data.symbol) == 0) { break; } curr = curr.next; } return curr; } //print contents of linked list. public void printList() { Node curr; curr = head; while (curr != null) { //print each node curr.print(); curr = curr.next; } } //insert a new node if key is not in the linked list. Otherwise increment frequency by 1. public void insert(String key) { Node curr; curr = search(key); if (curr == null) { //key not in list, add it to front. curr = new Node(key); //insert new node at front of list curr.next = head; head = curr; count = count + 1; } else { //already in list. Increment the frequency by 1. curr.data.frequency = curr.data.frequency + 1; //increment frequency of symbol } } } //A node of the Linked List class FrequencyList. class Node { FrequencyData data; Node next; Node(String key) { data = new FrequencyData(key,1); } void print() { data.print(); } } //This class contains a symbol and its frequency class FrequencyData { String symbol; //using a string type will become handy when build the Huffman encoding tree. int frequency; FrequencyData (FrequencyData data) { symbol = data.symbol; frequency = data.frequency; } FrequencyData(String s, int freq) { symbol = s; frequency = freq; } //print content of symbol (which may contain more than one character //for debugging purposes only. void printSymbol() { int i; int a; String s=""; for (i = 0; i < symbol.length(); i++) { a = (int) symbol.charAt(i); if (a==10) s = s+"<NEWLINE>"; //instead of printing a newline, print <NEWLINE> instead else if (a == 32) s =s+"<SPACE>"; //same for space else if (a == 9) s =s+"<TAB>"; //same for tab. Should probably do same for "escaped" characters else s = s+ symbol.charAt(i); } System.out.print(s); } /*used to print symbol(s) and frequency*/ /*used for debugging*/ void print() { printSymbol(); System.out.println(":"+frequency); } }