使用链接列表实现队列时出现NullPointerException

时间:2014-10-22 12:35:36

标签: java nullpointerexception queue

我正在关注Coursera算法1课程,现在正在使用链接列表实现队列,但获得NullPointerException。请帮帮我。

package algo_packages;

public class QueueLinkedList {
    private Node first, last;
    public class Node{
        String item;
        Node next;
    }

    public QueueLinkedList(){
        first = null;
        last = null;
    }
    public boolean isEmpty(){
        return first == last;
    }
    public void enqueue(String item){
        Node oldLast = last;
        last = new Node();
        last.item = item;
        last.next = null;
        if(isEmpty()){
            first = last;
        }
        else {
            oldLast.next = last;
        }
    }
    public String dequeue(){
        String item = first.item;
        first = first.next;
        if (isEmpty()) last = null;
        return item;
    }
}

我收到例外:

oldLast.next = last;
当我尝试调试程序时,

oldLast.next导致NullPointerException

2 个答案:

答案 0 :(得分:1)

第一次排队项目isEmpty()会返回false,因为它会检查first==last是否为first,但last仍为空且Node不再为空(因为您已经为其分配了新的oldLast.next。这样,您就可以在oldLast为空时访问NullPointerException,因此public void enqueue(String item) { Node oldLast = last; Node newNode = new Node(); newNode.item = item; newNode.next = null; if(isEmpty()) { // last is not assigned yet, so isEmpty returns correct result last = newNode; first = last; } else { last = newNode; oldLast.next = last; } }

可能的解决办法:

{{1}}

答案 1 :(得分:0)

当你检查isEmpty()时,它总是为enqueue返回false,因为你最后设置的是一个永远不会等于的新Node()。您不需要检查列表是否为isEmpty(),因为如果list为空,则首先== last,因此您不需要指定first = last,因为它们已经相等。试试这个:

public void enqueue(String item){
    Node oldLast = last;
    last = new Node();
    last.item = item;
    last.next = null;
    if(oldLast != null)
    {
        oldLast.next = last;
    }
    else
    {
        first = last;
    }
}