将节点插入优先级队列java

时间:2014-11-16 23:07:09

标签: java priority-queue

嗨我试图把我创建的所有节点都放到pq中,这样我就可以按重量排序它们然后删除前两个项目(最小的)所以我可以构建一个huffman树,这是一个专门的版本的二叉树最好的方法是什么?感谢

public class Main {

    public void main(String[] args) throws IOException {

        long start = System.currentTimeMillis();
        String inputFileName = args[0];
        FileReader reader = new FileReader(inputFileName);
        Scanner in = new Scanner(reader);

        // read in the data and do the work here
        // read a line at a time to enable newlines to be detected and allowed for

        while(in.hasNext()){
            CharacterMap<Character, Integer> hashMap = new CharacterMap<Character, Integer>();
            char[] chars = scanner.nextLine().toLowerCase().toCharArray();
            int c_count = 0;
            for (Character c : chars) {
                c_count += 1;
                if (hashMap.containsKey(c)) {
                    hashMap.put(c, hashMap.get(c) + 1);
                } else {
                    hashMap.put(c, 1);
                }
        }

            PriorityQueue<Node> pq = new PriorityQueue<Node>(new Comparator<Node>() {

            for (Map.Entry<Character, Integer> entry : hashMap.entrySet()){

                Node n = new Node();

                int f = entry.getValue();
                String c = entry.getKey();
                n.setWeight(f);
                n.setCharacter(c);

                n.setLeftChild(null);
                n.setRightChild(null);
                pq.add(n);
            }

        reader.close();

        String outputFileName = args[1];
        FileWriter writer = new FileWriter(outputFileName);
        writer.write("Input file " + inputFileName + "  Huffman algorithm\n\n");

        // write out the results here

        long end = System.currentTimeMillis();
        writer.write("\nElapsed time: " + (end - start) + " milliseconds");
        writer.close();
    }

}

1 个答案:

答案 0 :(得分:0)

如果您希望获得优先级队列的Java实现来按权重对节点进行排序,则必须使您的节点类实现&#34;可比较的&#34;接口。这意味着将&#34; compareTo&#34;节点类中的方法并按权重定义比较,例如:

private static class Node implements Comparable<Node>{
    public int compareTo(Node n) {
        if(this.weight < n.weight){
            return -1;
        }else if(this.weight > n.weight){
            return 1;
        }else
            return 0;
    }
}