2016-08-04 52 views
-2

採用鄰接表我想實現使用從以下資源鄰接表在Java中無向圖來實現圖形:http://www.geeksforgeeks.org/graph-and-its-representations/如何在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); 
    } 
} 

請幫忙!

+0

當前輸出是什麼? – CMPS

+0

我在終端沒有得到任何輸出。但在eclipse中,它引發了'NullPointerException'。 –

+0

是的,它是預計!我在我的答案中發佈了修復程序 – JavaHopper

回答

5

在撥打電話this.array[i].head之前,您尚未初始化array中的元素。因此你會得到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. 您可以遵循陣列甲骨文tutorial詳細地瞭解有關數組在Java中是如何工作的
  2. 我din't代碼
  3. 的重構等部位