Java 使用链表实现队列时出现NullPointerException
我正在学习Coursera算法1课程,现在使用链表实现队列,但得到了一个Java 使用链表实现队列时出现NullPointerException,java,nullpointerexception,queue,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(){
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
第一次将项目排入队列时isEmpty()
返回false,因为它检查first==last
,但是first
仍然为null,并且last
不再为null(因为您已经将新的节点分配给它)。这使您可以在oldLast
为空时访问oldLast.next
,因此出现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;
}
}
当您选中isEmpty()时,它总是为enqueue返回false,因为您将last设置为一个新节点(),该节点永远不会等于first。您不需要检查list是否为空(),因为如果list为空,那么first==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;
}
}
没问题,我很高兴能帮上忙!