I am getting the error java.lang.NullPointerException
while implementing priority queue with nodes. Does anyone have a solution without using built in priorityqueue
class?
class node { //NODE CLASS
public String ch;
public int freq;
node right_child, left_child;
public node(String ch, int freq) {
this.ch = ch;
this.freq = freq;
}
public String get_char() {
return ch;
}
public int get_freq() {
return freq;
}
}
//END NODE CLASS
class priority_queue {
private final int size;
private final node[] q_array;
private int no_items = 0;
public priority_queue(int max) {
this.size = max;
q_array = new node[size];
}
public void insert(node item) {
int j;
if (no_items == 0) {
q_array[++no_items] = item;
System.out.println("first item");
} else {
for (j = no_items - 1; j >= 0; j--) {
if (item.get_freq()> q_array[j].get_freq()) {
q_array[j + 1] = q_array[j];
} else {
break;
}
}
q_array[j] = item;
no_items++;
}
}
public node remove() {
return q_array[--no_items];
}
public void process() {
node first, second;
int new_freq;
while (q_array.length > 1) {
new_freq = 0;
first = this.remove();
//f1 = first.freq;
second = this.remove();
//f2=second.freq;
new_freq = first.get_freq() + second.get_freq();
node new_node = new node("*", new_freq);
new_node.left_child = first;
new_node.right_child = second;
this.insert(new_node);
}
}