简体   繁体   English

单个链表Java

[英]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;
}

} }

This is the sample program to insert data after a specified node in single linked list. 这是在单个链接列表中的指定节点之后插入数据的示例程序。 In the above program my question is why null pointer exception is happening at the following statements: 在上面的程序中,我的问题是为什么在以下语句中发生空指针异常:

specifiedNode.next = s4.next;
s4.next = specifiedNode;

why do you keep accessing the .next of the s4 instance? 为什么继续访问s4实例的.next? the way to do that is to store the s4.next in an attribute for one time and keep using it in all your program since each time you access the .next() you are invoking the next record and probably one of them is null; 这样做的方法是将s4.next在属性中存储一次,并在所有程序中继续使用它,因为每次访问.next()时,您都在调用下一条记录,并且其中一个可能为null。

In order to avoid a NullPointerException, ensure you always check on s4 not being 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM