我想把LinkList里面的元素全部删除干净。但是删除到最后一个元素时就会出现如下错误:
Exception in thread "main" java.lang.NullPointerException
at org.firstlastlist.kql.FirstLastList.deleteFirst(FirstLastApp.java:72)
at org.firstlastlist.kql.FirstLastApp.main(FirstLastApp.java:138)
我无法把最后一个元素删除掉,请问这是为什么? 非常感谢!
链表结构:
代码如下
package org.firstlastlist.abc;
/*
* demonstrates list with first and last references
* to run this program: C> java FirstLastApp
*/
/* ---- class Link ---- */
class Link{
public long dData; /* data item*/
public Link next; /* next link in list*/
public Link(long d){ //constructor
dData = d;
}
public void displayLink(){ // display this link
System.out.print("{"+dData+"}");
}
}// end class Link
/* ----class FirstLastList ---- */
class FirstLastList{
private Link first; // ref to first link
private Link last; // ref to last link
//--constructor--
public FirstLastList(){ // constructor
first = null; // no link on list yet
last = null;
}
//----isEmpty() method----
public boolean isEmpty(){ // true if no links
return (first==null);
/* if(first==null){
return true;
}
else
return false;
*/
}
//----insertFirst()----
public void insertFirst(long dd){ // insert at front of list
Link newlink = new Link(dd); // make new link
/* if(isEmpty()){*/ //this is right or ..
if(first==null){
//first = newlink;
last = newlink; //newlink<--last
}
else{
newlink.next = first; // newlink --> old first
//first = newlink;
}
first = newlink; // first-->newlink
}
//----insertLast()----
public void insertLast(long dd){ // insert at the end of list
Link newlink = new Link(dd);
if(isEmpty()){
first = newlink;
// last = newlink;
}
else{
last.next = newlink;
}
last = newlink;
}
//----deleteFirst()----
public Link deleteFirst(){// delete first link
Link temp= first;
if (first.next==null)
last = null;
first = first.next;
return temp;
}
//----displayList()----
public void displayList(){
Link current = first;
while(current != null){ // current.next!= null is wrong!!!
current.displayLink();