如何在Java中利用邻接表实现图形

如何在Java中利用邻接表实现图形,java,algorithm,data-structures,graph,adjacency-list,Java,Algorithm,Data Structures,Graph,Adjacency List,我试图使用以下资源中的邻接列表在Java中实现无向图: 代码运行时没有任何错误,但不提供任何输出。代码如下: class AdjListNode{ int dest; AdjListNode next; public AdjListNode(int dest){ this.dest = dest; this.next = null; } } class AdjList{ AdjListNode head; } publ

我试图使用以下资源中的邻接列表在Java中实现无向图:

代码运行时没有任何错误,但不提供任何输出。代码如下:

class AdjListNode{
    int dest;
    AdjListNode next;

    public AdjListNode(int dest){
        this.dest = dest;
        this.next = null;
    }
}

class AdjList{
    AdjListNode head;
}

public class graph{
    int V;
    AdjListNode newNode;
    AdjList array[];

    public graph(int V){
        this.V = V;
        this.array = new AdjList[V];
        int i;
        for(i=0;i<V;++i){
            this.array[i].head = null;
        }
    }

    void addEdge(graph g, int src, int dest){
        newNode = new AdjListNode(dest);
        newNode.next = g.array[src].head;
        g.array[src].head = newNode;

        newNode = new AdjListNode(src);
        newNode.next = g.array[dest].head;
        g.array[dest].head = newNode;
    }

    void printGraph(graph g){
        int v;
        for(v=0;v < g.V;++v){
            AdjListNode pCrawl = g.array[v].head;
            System.out.println();
            System.out.println("Adjacency list of vertex "+v);
            System.out.print("head");
            while(pCrawl != null){
                System.out.print(pCrawl.dest);
                pCrawl = pCrawl.next;
            }
            System.out.println();
        }
    }

    public static void main(String[] args){
        int V = 5;
        graph g = new graph(V);
        g.addEdge(g,0,1);
        g.addEdge(g,0,4);
        g.addEdge(g,1,2);
        g.addEdge(g,1,3);
        g.addEdge(g,1,4);
        g.addEdge(g,2,3);
        g.addEdge(g,3,4);

        g.printGraph(g);
    }
}
类AdjListNode{
int dest;
AdjListNode下一步;
公共AdjListNode(int dest){
this.dest=dest;
this.next=null;
}
}
类调整列表{
节头;
}
公共类图{
INTV;
AdjListNode新节点;
AdjList数组[];
公共图形(INTV){
这个,V=V;
this.array=新的调整列表[V];
int i;

对于(i=0;i在调用
this.array[i].head
之前,您还没有使用
数组中的
初始化元素。因此您将获得
NullPointerException
。以下修复应该可以工作

public graph(int V){
    this.V = V;
    this.array = new AdjList[V];
    int i;
    for(i=0;i<V;++i){
        this.array[i] = new AdjList();
    }
}
公共图形(int V){
这个,V=V;
this.array=新的调整列表[V];
int i;

对于(i=0;i当前输出是什么?我在terminal中没有得到任何输出。但是在eclipse中,它引发了
NullPointerException
。是的,这是预期的!我已经在回答中发布了修复