小编典典

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

java

在双头链表中,我使用了另一个链接theLink,该链接通过copy构造函数复制到copy
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);


}

}


阅读 484

收藏
2020-11-30

共1个答案

小编典典

问题似乎出在方法上insertBelow。您有条件继续前进,直到node traversal不为null 为止:

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

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

lastLink = traversal;

现在lastLink为null,下一行:

 lastLink.next = toInsert;

正在尝试访问null,因此是NPE的问题。您需要通过将while循环条件更改为以下内容来修复代码:

 while(traversal.next!=null)
2020-11-30