在双头链表中,我使用了另一个链接theLink,该链接通过copy构造函数复制到copy firstLink。但是,当我遍历链接列表从后端插入时,它抛出了一个空指针异常。
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); }
}
问题似乎出在方法上insertBelow。您有条件继续前进,直到node traversal不为null 为止:
insertBelow
traversal
while(traversal!=null){ traversal = traversal.next; }
当while循环结束时,traversal将指向null位置。然后在下一行:
null
lastLink = traversal;
现在lastLink为null,下一行:
lastLink
lastLink.next = toInsert;
正在尝试访问null,因此是NPE的问题。您需要通过将while循环条件更改为以下内容来修复代码:
while(traversal.next!=null)