Привет, я пытаюсь получить все узлы, которые я создаю в pq, поэтому я могу упорядочить их по весу, а затем удалить первые два элемента (самый маленький), чтобы я мог построить дерево huffman которая является специализированной версией двоичного дерева, как лучший способ сделать это? БлагодаряВставка узлов в очередь приоритетов java
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();
}
}
Возможно, вы сделали это уже при быстрой проверке кода. Что за вопрос? – EJP
Как только я их добавлю, я не уверен, как получить очередь, чтобы упорядочить их по весу. Одна из переменных экземпляра узлов. –