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. I tried
第一个数字是边的数目。在那之后,边被列出。看到例如顶点1有多个不同的边缘,我想跟踪1连接到什么,我在想,每个顶点的图会有某种的顶点列表连接到这让我试着创建一个数组链表,但我不知道我会这样做。我试着
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.
但是我在添加行得到nullpointerexception。
2 个解决方案
#1
20
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++;
}
#2
2
//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. Alternatively you can use this:
通常在Java中不鼓励数组。或者你也可以用这个:
//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>());
#1
20
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++;
}
#2
2
//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. Alternatively you can use this:
通常在Java中不鼓励数组。或者你也可以用这个:
//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>());