gpt4 book ai didi

java - 双向链表-再次出现空指针异常

转载 作者:行者123 更新时间:2023-12-01 15:30:31 24 4
gpt4 key购买 nike

我收到此异常,这似乎是我正在使用空节点执行操作。有人可以解释我是怎么做的吗?构造函数应该是什么样子?我看到它是空的或带有 header 和标尾虚拟节点..

    //default constructor
public AddressList() {

}

//get size
public int size() {
return counter;
}

public void addEntryNode(){
//create the new node
EntryNode n = new EntryNode();
//set the data
System.out.println("Enter first name: ");
n.myFirstName = keyboard.next();
n.setFirstName(n.myFirstName);

System.out.println("Enter Last Name: ");
n.myLastName = keyboard.next();
n.setLastName(n.myLastName);

System.out.println("Enter Email Address: ");
n.myEmail = keyboard.next();
n.setEmail(n.myEmail);

System.out.println("Enter Phone Number: ");
n.myPhoneNum = keyboard.next();
n.setPhoneNum(n.myPhoneNum);

n.setIndex(index);

//add nodes to head of list
head.setPrev(n);
n.setNext(head);
head = n;

//up the count and index
counter++;

最佳答案

嗯,这似乎是最有可能的解决办法。将 head 初始化为 null,并添加列表为空时的条件。

public AddressList() {
head = null
}

你的情况如下:

if (head == null) {  // empty list
head = n
}
else {
head.setPrev(n);
n.setNext(head);
head = n;
}

关于java - 双向链表-再次出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9576483/

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