How to create a linked list array in Java?
•
Java
So I need to input the 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 sides Then list the edges Seeing how vertex 1 has multiple different edges, I want to track what 1 is connected to. I'm thinking that each vertex of the graph will have some lists. The vertices it connects lead me to try to create a linked list array, but I don't know what to do 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 on the addition line
Solution
LinkedList<Integer>[] vertex = new LinkedList[5];
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++;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
