使用节点实现优先级队列时的nullpointerexception

时间:2017-06-04 17:46:05

标签: java priority-queue

在实现带节点的优先级队列时,我收到错误java.lang.NullPointerException。有没有人使用内置priorityqueue类的解决方案?

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

        }

    }

1 个答案:

答案 0 :(得分:0)

您不能向q_array[0]添加任何内容。当no_items为0时,您首先将其增加,然后插入具有1个位置的元素。这就是q_array[++no_items]的工作原理。 因此,第二次插入时,q_array[j].get_freq()中有NPE。