1
System.out.println("insert after specified data node");
System.out.println("enter data");
int x = sc.nextInt();
Node s4 = head;
try
{
while(s4.data != x)
{
s4 = s4.next;
}
}
catch(NullPointerException e)
{
e.printStackTrace();
}
System.out.println("hi");
Node specifiedNode = new Node(x);
//s4.next = specifiedNode;
try
{
specifiedNode.next = s4.next;
s4.next = specifiedNode;
}
catch(NullPointerException e)
{
e.printStackTrace();
}
System.out.println("output after specified insertion");
Node s5 = head;
while(s5!=null)
{
System.out.println(s5.data);
s5 = s5.next;
}
这是示例程序中单链表指定节点之后插入的数据。在上面的程序我的问题是,为什么空指针异常是发生在下面的语句:
specifiedNode.next = s4.next;
s4.next = specifiedNode;
请尝试创建一个[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)并向我们显示。 –
您需要编写并绘制您正在尝试完成的任务。这个实现是离开的。 – Sedrick
'while(s4.data!= x)s4 = s4.next;'基本上,如果你没有列表中的'x',它就会失败......你不应该抓住NPE,而是要管理它们。对于_“为什么?”_,你只需检查一下值? – AxelH