简体   繁体   English

如何在java中创建一个链表数组?

[英]How can I create an array of linked lists in java?

So I need to take in input of edges of a bipartite graph like this:所以我需要像这样输入二部图的边:

6
1 3
1 2
1 5
2 7
2 4
2 9

The first number is the number of edges.第一个数字是边的数量。 After that edges are listed.之后列出边。 See how for example vertex 1 has multiple different edges and I want to keep track of what 1 is connected to, I was thinking that each vertex of the graph would have some sort of list of vertices it is connected to which leads me to try to create an array of linked lists but I'm not sure how I would do that.看看例如顶点 1 如何有多个不同的边,我想跟踪 1 连接到什么,我在想图形的每个顶点都会有某种它所连接的顶点列表,这导致我尝试创建一个链表数组,但我不确定我会怎么做。 I tried我试过

LinkedList<Integer>[] vertex = new LinkedList[5];
int i = 0, m = 6;
while(i!=m){
    int temp = sc.nextInt();
    int temp2 = sc.nextInt();
    vertex[temp].add(temp2);
    i++;
}

But I get a nullpointerexception at the add line.但是我在添加行得到了一个空指针异常。

LinkedList<Integer>[] vertex = new LinkedList[5];
int i = 0, m = 6;
while(i!=m){
  int temp = sc.nextInt();
  int temp2 = sc.nextInt();

  // Make sure the list is initialized before adding to it
  if (vertex[temp] == null) {
     vertex[temp] = new LinkedList<Integer>();
  }

  vertex[temp].add(temp2);
  i++;
}
//initialize array
LinkedList<Integer>[] vertex = new LinkedList[5];
//initialize array elements(objects of LinkedList)
for (int j=0; j<5; j++)
    vertex[i]=new LinkedList<Integer>();

int i = 0, m = 6;
while(i!=m){
    int temp = sc.nextInt();
    int temp2 = sc.nextInt();
    vertex[temp].add(temp2);
    i++;
}

Normally Arrays are not encouraged in Java.通常,Java 中不鼓励使用数组。 Alternatively you can use this:或者你可以使用这个:

//initialize array
List<LinkedList<Integer>> vertex = new ArrayList<LinkedList<Integer>>();
//initialize arraylist elements(objects of LinkedList)
for (int j=0; j<5; j++)
    vertex.add(new LinkedList<Integer>());

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

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