Traversing through Linked List throws me a Null Pointer exception [duplicate]

血红的双手。 提交于 2020-01-11 14:33:52

问题


In a double ended Linked List, , I used another Link theLink which is copied through copy constructor to copy firstLink . But when I iterate through Linked List to insert from the back end , It throws me a Null Pointer Exception.

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:


The problem seems to be with the method insertBelow. You have the condition to keep on going until node traversal is not null:

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

When the while loop is over traversal will be pointing to null location. Then in next line:

lastLink = traversal;

Now lastLink is null and the next line:

 lastLink.next = toInsert;

is trying to access null and hence the problem of NPE. You need to fix the code by changing while loop condition as:

 while(traversal.next!=null)


来源:https://stackoverflow.com/questions/32163463/traversing-through-linked-list-throws-me-a-null-pointer-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!