简体   繁体   English

Java中的多个链接列表

[英]Multiple Linked Lists in Java

I am trying to create multiple linked list in java, but at one of the lines i am getting NullPointerException and i am unable to find out the reason as to why such error is arising. 我正在尝试在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引用。

You have defined a node array but not populated it with anything, so 您已经定义了节点数组,但未填充任何内容,因此

head[x]

refers to a null item, and using it to access the .data field results in an NPE. 引用一个空项目,并使用它来访问.data字段将导致NPE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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