2017-09-14 19 views
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; 
} 

}单链表的java

这是示例程序中单链表指定节点之后插入的数据。在上面的程序我的问题是,为什么空指针异常是发生在下面的语句:

specifiedNode.next = s4.next; 
s4.next = specifiedNode; 
+0

请尝试创建一个[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)并向我们显示。 –

+0

您需要编写并绘制您正在尝试完成的任务。这个实现是离开的。 – Sedrick

+0

'while(s4.data!= x)s4 = s4.next;'基本上,如果你没有列表中的'x',它就会失败......你不应该抓住NPE,而是要管理它们。对于_“为什么?”_,你只需检查一下值? – AxelH

回答

0

你为什么老是访问S4实例。接下来? 要做到这一点的方法是将s4.next存储在属性中一次,并继续在您的所有程序中使用它,因为每次访问.next()时,都会调用下一条记录,并且可能其中一个为null ;

0

为了避免NullPointerException,请确保您始终检查s4不为空。

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. 
}