这里我使用一个不同的类来实现使用邻接List.I几乎所有的东西,但我仍然得到这个错误
public class Breadth_first_Traversal {
Graph g;
void BFS(int s,int v){
boolean[] visited=new boolean[v];
LinkedList<Integer> q1=new LinkedList<Integer>();
q1.add(s);
visited[s]=true;
while(q1.size()!=0){
s=q1.poll();
System.out.print(s+" ");
Iterator<Integer> i=g.adj[s].listIterator();
while(i.hasNext()){
int n=i.next();
if(!visited[n]){
q1.add(n);
visited[n]=true;
}
}
}
}
public static void main(String args[]){
Breadth_first_Traversal bfs=new Breadth_first_Traversal();
Graph gr=new Graph(4);
gr.addEdge(0, 1);
gr.addEdge(0, 2);
gr.addEdge(1, 2);
gr.addEdge(2, 0);
gr.addEdge(2, 3);
gr.addEdge(3, 3);
bfs.BFS(2, 4);
}
输出
2 Exception in thread "main" java.lang.NullPointerException
at Graph_data_structure.Breadth_first_Traversal.BFS(Breadth_first_Traversal.java:21)
at Graph_data_structure.Breadth_first_Traversal.main(Breadth_first_Traversal.java:40)Picked up _JAVA_OPTIONS: -Xmx512MJava Result: 1BUILD SUCCESSFUL (total time: 1 second)
请帮忙。