[英]Multiple Linked Lists in Java
我正在嘗試在Java中創建多個鏈接列表,但是在其中一行中,我遇到了NullPointerException,並且我無法找出出現此類錯誤的原因。
import java.util.*;
class node{
int data;
node link;
public node(){
data = 0;
link = null;
}
}
public class ll{
static node add(node head[], int x){
node temp = new node();
System.out.println("Enter value");
temp.data = new Scanner(System.in).nextInt();
temp.link = head[x].link;
head[x].link = temp;
return head[x];
}
public static void main(String []args){
int m =0;
int x = 0; int flag = 0;
System.out.println("Enter the size of index");
m = new Scanner(System.in).nextInt();
node []head = new node[m];
while(x<head.length){
head[x].data = 0; //error arises here
head[x].link = null;
x++;
}
System.out.println(head[0].data); //error arises here.
}
}
那是因為head[x]
/ head[0]
包含null
引用。
您已經定義了節點數組,但未填充任何內容,因此
head[x]
引用一個空項目,並使用它來訪問.data字段將導致NPE。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.