遍历链接列表会抛出一个空指针异常

时间:2015-08-23 05:22:45

标签: java linked-list

在双端链接列表中,我使用了另一个链接theLink,它通过复制构造函数复制到firstLink。但是当我遍历链接列表从后端插入时,它会抛出一个空指针异常。

package javaapplication2;

import java.util.Arrays;

public class DoubleEndedLinkList {

Link firstLink;
Link lastLink;
int data;


public boolean isEmpty() {
    return firstLink == null;
}

public void insertAbove(int data) {
    Link toInsert = new Link(data);

    if (isEmpty()) {
        firstLink = toInsert;
    } else {
       // System.out.println("firstLink : " + firstLink.data);
        toInsert.next = firstLink;
        firstLink = toInsert;
    }
}

public void insertBelow(int data) {
   Link toInsert = new Link(data);
   if(isEmpty()){
       lastLink = toInsert;
   }else{
       Link traversal = new Link(firstLink);
       while(traversal!=null){
           traversal = traversal.next;
       }
       System.out.println("LastLink = " + traversal.data ); //Here exception occurs 
       lastLink = traversal;
       lastLink.next = toInsert;
       lastLink = toInsert;
   }
}

public void display() {
    Link theLink = firstLink;
    try {
        System.out.print(theLink.data + "->");
        theLink = theLink.next;
        while (theLink != null) {
            System.out.print(theLink.data + "->");
            theLink = theLink.next;
        }
        System.out.print("||");

    } catch (NullPointerException e) {
        System.out.print("->||");
    }

}



@Override
public String toString() {
    return String.valueOf(data);
}


public static void main(String[] args) {

    DoubleEndedLinkList dl = new DoubleEndedLinkList();
    dl.insertAbove(5);
    dl.insertAbove(10);
    dl.insertAbove(15);
    dl.display();
    dl.insertBelow(99);
    System.out.println("FirstLink = " + dl.firstLink.data + " LastLink = " + dl.lastLink.data);


}

}

1 个答案:

答案 0 :(得分:1)

问题似乎与方法insertBelow有关。您有条件继续前进,直到节点traversal不为空:

 while(traversal!=null){
      traversal = traversal.next;
 }

当while循环结束时traversal将指向null位置。然后在下一行:

lastLink = traversal;

现在lastLink为空并且下一行:

 lastLink.next = toInsert;

正在尝试访问null,从而导致NPE问题。您需要通过将while循环条件更改为:

来修复代码
 while(traversal.next!=null)