所以我需要接受二部图的边的输入,如下所示:
6
1 3
1 2
1 5
2 7
2 4
2 9
第一个数字是边数。然后列出边。例如,顶点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++;
}
但是我在add行得到了一个nullpointerexception。
发布于 2016-08-11 05:23:05
//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++;
}
通常,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>());
https://stackoverflow.com/questions/20202889
复制相似问题