当前位置: 代码迷 >> Eclipse >> 双端链表删除最后一个元素报错 怎么解决 非常感谢
  详细解决方案

双端链表删除最后一个元素报错 怎么解决 非常感谢

热度:503   发布时间:2016-04-23 01:22:50.0
双端链表删除最后一个元素报错 如何解决 非常感谢!
本帖最后由 dreamzhenzhen 于 2013-05-23 15:28:47 编辑
我想把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();
  相关解决方案