问题
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