如何在Java中使用Adjacency List实现Graph

时间:2016-08-04 17:59:08

标签: java algorithm data-structures graph adjacency-list

我正在尝试使用以下资源中的邻接列表在Java中实现无向图:http://www.geeksforgeeks.org/graph-and-its-representations/

代码运行没有任何错误但不提供任何输出。这是代码:

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);
    }
}

请帮忙!

1 个答案:

答案 0 :(得分:4)

在拨打array之前,您尚未在this.array[i].head内初始化元素。因此,您将获得NullPointerExcpetion。以下修复工作

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();
    }
}

注意:

  1. 您可以在数组上关注Oracle tutorial,以详细了解数组如何在Java中工作
  2. 我不会重构您代码的其他部分