-1

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);

        }

    }
Radiodef
  • 37,180
  • 14
  • 90
  • 125
sawyer
  • 1
  • 4

1 Answers1

0

You don't add anything to q_array[0]. When no_items is 0 you're increasing it first and then insert the element with 1 position. That is how q_array[++no_items] works. Hence you have NPE in q_array[j].get_freq() for the second insertion.

nickolay.laptev
  • 2,253
  • 1
  • 21
  • 31
  • I have modified it accordingly as below, q_array[no_items] = item; no_items++;.but still getting NPE.......:( – sawyer Jun 04 '17 at 18:53
  • Then you have one more problem. NPE has a stack trace that points to the problem place. Please provide it here. – nickolay.laptev Jun 04 '17 at 19:05