[英]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.