所以我在这里要做的是检查一个对象是否存在通过if(x.next==null)
,我得到一个错误,这将不允许我访问一个空对象。我也得到同样的错误时,试图修改一个对象,例如x.next=y
代码很简单,它只是实现一个链表。谢谢!
//import SingleLinkedList1.Node;
public class SingleLinkedList2 implements ISimpleList2 {
private class Node
{ int value;
Node next; }
private Node first;
private Node last;
public void insertFront(int item) {
// TODO Auto-generated method stub
Node oldfirst = first;
// Create the new node
Node newfirst = new Node();
newfirst.value = item;
newfirst.next = oldfirst;
// Set the new node as the first node
first = newfirst;
if(oldfirst.next==null){
last=first;
}
}
public int removeFront() {
// TODO Auto-generated method stub
// Save the previous first
Node oldfirst = first;
if(oldfirst.next==null){
last=null;
}
// Follow the first's node (possibly empty)
// and set the first to that pointer
first = oldfirst.next;
// Return the value of old first
return oldfirst.value;
}
public void insertEnd(int item) {
// TODO Auto-generated method stub
Node newLast=new Node();
newLast.value=item;
last.next=newLast;
last=newLast;
}
public int removeEnd() {
// TODO Auto-generated method stub
Node oldLast=last;
Node check=new Node();
check=first;
while(check.next!=last ){
check=check.next;
}
last=check;
return oldLast.value;
}
public boolean isEmpty()
{
if(first.next==null){
return true;
}
else{
return false;
}
}
}
这很常见。你必须确保对象本身不是空的。
在你的检查if(x.next==null)
x.next
的评估抛出一个NullPointerException,因为x本身是Null。
。在isEmpty方法中,你必须检查是否(first==null)
我认为你应该检查x
,可以是null.
就像代码f(x == null)
一样,因为如果x
为空,那么你将得到NullPointException
。