[英]single linked list java
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;
为什么继续访问s4实例的.next? 这样做的方法是将s4.next在属性中存储一次,并在所有程序中继续使用它,因为每次访问.next()时,您都在调用下一条记录,并且其中一个可能为null。
为了避免NullPointerException,请确保始终检查s4
不为null。
Node s4 = head; // Head initially is null (empty list).
while (s4 != null) { // End reached?
if (s4.data == x) {
// Wow, found x.
break; // Jump out of the loop.
}
// Go to next node.
s4 = s4.next; // s4 could become null.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.