3
将节点添加到链接的末尾时遇到问题 代码非常明显,addToEnd方法将单个节点添加到链表的末尾。将节点添加到链表末尾
public class ll5 {
// Private inner class Node
private class Node{
int data;
Node link;
public Node(int x, Node p){
data = x;
link = p;
}
}
// End of Node class
public Node head;
public ll5(){
head = null;
}
public void addToEnd(int data) {
Node p = head;
while (p.link != null)
p=p.link;
p.link=new Node(data, null);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ll5 list = new ll5();
list.printList();
System.out.println("How many values do you want to add to the list");
int toAdd = input.nextInt();
for(int i = 0; i < toAdd; i++) {
System.out.println("Enter value " + (i + 1));
list.addToEnd(input.nextInt());
}
System.out.println("The list is:");
list.printList();
input.close();
}
}
为什么它给了我一个NullPointerException错误?该错误位于addToEnd方法的while循环中。
我想,'节点p = head'使得'P = null'因为'head'是'null'当你调用'addToEnd '第一次。 – StepTNT