gpt4 book ai didi

java - 遍历链表会引发空指针异常

转载 作者:行者123 更新时间:2023-12-02 04:25:57 24 4
gpt4 key购买 nike

在双端链表中,我使用了另一个链接 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 方法上。你有条件继续下去,直到节点遍历不为空:

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

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

lastLink = traversal;

现在 lastLink 为空,下一行:

 lastLink.next = toInsert;

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

 while(traversal.next!=null)

关于java - 遍历链表会引发空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32163463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com